"Second" ASP-Quick Start Data annotations (MVC5+EF6)

Source: Internet
Author: User
Tags http post mssql server table definition connectionstrings

Directory

First ASP. NET MVC QuickStart Database Operations (MVC5+EF6)

"Second" ASP-Quick Start Data annotations (MVC5+EF6)

"Third" security policy for the Quick start of ASP. NET MVC (MVC5+EF6)

"Fourth" complete example of the ASP. NET MVC QuickStart (MVC5+EF6)

The Free jquery Control Library (MVC5+EF6), "Foreign article", the Quick start of ASP.

Please pay attention to the three stone blog: Http://cnblogs.com/sanshi

Database connection string

In the previous article, we used the MVC template to automatically generate all of the crud operations, but no database connection strings were configured, so where did the data go?

Open the project's App_Data directory and you can find the database originally here:

We take a look at the table structure and the data in the database access tool that comes with VS, first find the Server Explorer panel and add a database connection:

In the Add Connection Wizard dialog box, enter the server name: (LocalDb) \mssqllocaldb, this is the name of the server instance that VS2015 comes with LocalDb (if you use VS2013, the name may be: (LocalDb) \v11.0). Database Select the Studentdbcontext we just created.

If the database connection string is not explicitly specified, VS uses the default LocalDB instance, which is defined in Web. config:

<entityFramework>       <defaultconnectionfactory type= " System.Data.Entity.Infrastructure.LocalDbConnectionFactory, entityframework ">         <parameters>             <parameter value= "mssqllocaldb"/>         </parameters>       </defaultConnectionFactory>       <providers>         <provider invariantname= "System.Data.SqlClient" type= "System.Data.Entity.SqlServer.SqlProviderServices, Entityframework.sqlserver"/>       </providers></entityFramework>

Of course, we can also explicitly specify a database connection string:

<connectionStrings>       <add name= "defaultconnection" connectionstring= "Data source=(LocalDb) \ Mssqllocaldb; attachdbfilename=| Datadirectory|\aspnetmvc.quickstart.models.studentdbcontext.mdf;initial catalog= aspnetmvc.quickstart.models.studentdbcontext;integrated security=true "         providername=" System.Data.SqlClient " /></connectionstrings>

The database connection string is then referenced in the code:

public class studentdbcontext:dbcontext{       base ("DefaultConnection")       {       }        Public Dbset<student> Students {get; set;}}

Note: If the vs2013,data source used should be (LOCALDB) \v11.0, and VS2015 corresponds to (LocalDb) \mssqllocaldb.

After this change, when really deployed to the MSSQL server, simply modify the database connection string is enough.

database table Structure

Open the table definition for students:

You can see how EF maps the student model to the database table structure:

    1. The data map for the id attribute in the model is the primary key of the table.
    2. The string type in the model is mapped to the nvarchar (MAX) of the table.
    3. The int and datetime in the model are mapped to the INT and datetime types of the table, respectively.

Then look at the data that you added to the table in the previous article:

If you have previous experience with database design, it is easy to see the problem with this table structure:

    1. Name and major store strings, which generally need to limit the maximum length, such as nvarchar (200).
    2. The name and major columns should not be allowed to be empty.

So how do we achieve these two needs? Modifying the database directly is definitely not going to work!

Data annotations

We should start with the model, remember what we said at the end of the last article, the data model not only affects the table structure of the database, but also controls the client authentication of the MVC view layer and server-side validation of the controller layer.

Modify the Student model class to add the appropriate data annotations:

public class student{Public       int ID {get; set;}        [Required]       [Stringlength ($)]       public string Name {get; set;}        public int Gender {get; set;}        [Required]       [Stringlength ($)]       public string Major {get; set;}        Public DateTime entrancedate {get; set;}}

If there is no IntelliSense when entering [Required], it is likely that there is no reference to the appropriate namespace, vs can easily assist us in adding:

This will add the following reference to the file header:

Using System.ComponentModel.DataAnnotations;

Run the project directly (CTRL+F5), at which point we will see the following error page:

I believe that the students using EF will encounter this page, the above hints are also very clear, contains two levels of information:

    1. The model changed after the database was created.
    2. You can use data migration to update the database.

Data Migration (migrations)

From the VS [tools] menu, find the NuGet Package Manager console:

Enable Data migration

Enter the following command in the console: enable-migrations

In this case, a migrations folder is added to the project directory with two files placed in it:

EF saves each modification of the model to this folder in C # code, and now looks at the resulting file content:

Each migration file contains up and down two override functions that correspond to updates and rollbacks, respectively. The above code is also straightforward, the UP function creates a students table, defines the table structure and specifies the ID primary key (PrimaryKey), and the down function is used to rollback the operation, which simply deletes the students table.

As you can see, the CREATE TABLE operation here does not use the latest model (the Name column does not have a nullable setting), because this is the table structure for the initial model, and EF automatically generates a table named __migrationhistory in the database to track the state of the database.

Adding migration items

To add a migration entry we need to do this manually, in the Package Manager console, enter the following command:

Add-migration Add_annotation_name_major

In this case, the migration files are generated in the Migrations directory, and the files are named after [Time + migration name] for easy searching:

201612160406415_add_annotation_name_major.cs

Update to Database

At this point, the database has not changed, and we also need to update the database by hand:

Update-database

Then, look at the table structure of students in the database:

The data type of the name column and whether NULL is allowed have changed.

In a real project, the database might be deployed on a remote server, and we wouldn't be able to update the database directly with Update-database in VS.

But we can generate an update SQL script and get it executed on the database server. How to generate this SQL script:

Update-database-script

-sourcemigration:initialcreate

-targetmigration:add_annotation_name_major

Look at the generated SQL update script:

With this SQL update script, we can easily update the remote database.

Client-side validation of the view

Now run the project and go to the Create page:

As you can see, if name is empty there will be an error message, and the major input string is too many, and there will be a hint, and these settings are data annotations from the model.

This client authentication is provided by the validation plugin with jquery:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

If you look at the source code of the page, you will find that the input label of the major entry box has the corresponding custom attributes data-val-length-max=200 and Data-val-length, and these attribute values are the data annotations from the model.

Server-side validation of the controller

In the case of JavaScript enabled, because all the wrong input is intercepted on the client, it cannot reach the server at all, but this does not mean that the malicious user cannot submit the wrong input, there are many ways to do it:

Disable JavaScript

Different browsers disable JavaScript in different ways, in Chrome, F12 opens the developer tool and then finds the Settings dialog box:

At this point, you will see the page that is exactly the same as before, and you may not even be aware that you have initiated an HTTP POST request, and the page that displays the error prompt is from the server, not the client, because the local run is fast!

The response body contains the following, where the error message is generated on the server side:

<div class= "Form-group" >       <label class= "Control-label col-md-2" for= "Name" >Name</label>       <div class= "col-md-10" >              <input class= "Input-validation-error form-control text-box single-line" Data-val= "true" data-val-length= "field Name must be a string with a maximum length of 200. "Data-val-length-max=" the "data-val-required=" Name field is required. "id=" name "name=" name "type=" text "value=" "/> <span              class=" Field-validation-error Text-danger " Data-valmsg-for= "Name" data-valmsg-replace= "true" >name field is required. </span>       </div></div>

Now look back at the definition of the Create action method in the students controller:

[HttpPost] [Validateantiforgerytoken]public actionresult Create ([Bind (Include = "id,name,gender,major,entrancedate")] Student Student) {       if (modelstate.isvalid)       {              db. Students.add (student);              Db. SaveChanges ();              Return redirecttoaction ("Index");       }        Return View (student);}

If the validation fails, the database is not updated and the view with the student model is returned.

Simulate a POST request

There are many tools to simulate post, here we explain if using Fiddler to impersonate the item server to submit a POST request.

When we open fiddler, we start to automatically monitor all HTTP requests, and when we refresh the Create page and submit the form with JavaScript disabled, there are two requests:

First select the second request on the left, select Inspectors->webforms in the right panel, and three panes appear below:

    1. QueryString: The URL query string for the current request.
    2. Body:post the requested form parameter.
    3. Part Three: The response body, we can see the error message returned by the server side.

Now switch to the Composer tab, where we can simulate the POST request:

Here's a tip: Use this page to create a request. You can use drag-and-drop to copy a previous request from the list of left sessions.

This is much more convenient, we select a second request from the left and drag it to this page:

When the page background becomes obvious green to be prompted, drag the end:

At this time, Fiddler automatically helped us set the parameters of the analog post request, copied from a previous request, then the [request Body] is URL-encoded, we can easily decode:

Let's modify this code to:

__requestverificationtoken= Wwoxicdootbixw8ymifiou1ww95qscicreswleewlsae28sdyea0zchly0nfuolxu2wdijcrx086gykaboatewyarwberzp0kd6trt-hyas1 &name= Zhang Sanxi &gender=1&major=&entrancedate=2000-09-01

Copy this string to [Request Body] in fiddler and click on the [Execute] button, and a new impersonation request will be initiated:

Note that this request was not made from the page, but rather the HTTP POST request that was simulated by the tool, and we also modified the form parameters (Name= Zhang Sanxi, major= empty string), which would of course avoid the browser-side JavaScript validation rules. However, there is still no way to penetrate server-side validation.

This is also the convenience of data annotations in MVC, a local definition, three places to use (database table structure, client authentication, server-side validation).

Summary

In this chapter we first look at the database structure that EF automatically generates, then add data annotations to the data model, and then describe the process of data migration. Data annotations not only affect the structure of the database table, but also apply to the front-end client authentication and server-side validation, followed by a detailed explanation of the two ways to evade client authentication, respectively, to disable JavaScript and analog post requests. Thus a deeper understanding of the convenience provided by the data annotations: a local definition, three places to use (database table structure, client authentication, server-side validation)

In the Create new user page, we can see two security-related code (Validateantiforgerytoken and BIND), which are used to block CSRF cross-site request forgery and over-posting too many commit attacks, which we'll cover in detail in the next article.

Download Sample source code

"Second" ASP-Quick Start Data annotations (MVC5+EF6)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.