Four authentication programming methods under ASP. net mvc, asp. netmvc
Source Address http://www.cnblogs.com/artech/p/asp-net-mvc-validation-programming.html
ASP. net mvc uses Model binding to generate a list of corresponding parameters for the target Action. However, before the actual execution of the target Action method, it is necessary to verify the bound parameters to ensure their effectiveness, we will verify the parameters as Model binding. In general, we can use four different programming modes to verify binding parameters.
Directory
1. Manually verify the bound parameters
Ii. Use the ValidationAttribute feature
Iii. Implement the IValidatableObject interface for Data Types
Iv. Implement the IDataErrorInfo interface for Data Types
1. Manually verify the bound parameters
When defining specific Action methods, manual verification of successfully bound parameters is undoubtedly the most direct programming method, next, we will use a simple example to demonstrate how to implement the parameter verification logic in the corresponding Action method, and respond the error information to the client without passing the verification. In an ASP. the net mvc application defines the next Person class as the verified data type. Its Name, Gender, and Age attributes indicate a Person's Name, Gender, and Age respectively.
1: public class Person
3: [DisplayName ("name")]
4: public string Name { get; set; }
5:
7: public string Gender { get; set; }
8:
10: public int? Age { get; set; }
2: {
4: public ActionResult Index()
6: return View(new Person());
8:
10: public ActionResult Index(Person person)
12: Validate(person);
13:
15: {
16: return View(person);
18: else
20: return Content ("Verification of input data ");
22: }
23:
25: {
27: {
28: ModelState. AddModelError ("Name", "'name' is a required field ");
30:
32: {
33: ModelState. AddModelError ("Gender", "'gender' is a required field ");
35: else if (!new string[] { "M", "F" }.Any(g => string.Compare(person.Gender, g, true) == 0))
37: ModelState. AddModelError ("Gender", "valid 'gender' must be 'M', one of 'F ");
39:
41: {
42: ModelState. AddModelError ("Age", "'age' is a required field ");
44: else if (person.Age > 25 || person.Age < 18)
46: ModelState. AddModelError ("Age", "valid 'age' must be between 18 and 25 years old ");
48: }
49: }
As shown in the code snippet above, in the Validate method, we verify the three attributes of the Person object as the parameter one by one. If the provided data is not verified, we will call the AddModelError method of the current ModelState to convert the specified verification error message to ModelError and save it. The specific verification rules we adopt are as follows.
- The Name, Gender, and Age attributes of the Person object are required fields and cannot be Null (or an empty string ).
- Gender attribute value of Gender must be "M" (Male) or "F" (Female), and other values are invalid values.
- The Age attribute indicates that the Age must be between 18 and 25 years old.
The following is the definition of the View corresponding to the Action Method Index. This is a strong type View with the Model type "Person". It contains a form for editing personnel information. We directly call the extension method EditorForModel of HtmlHelper <TModel> to render the Model Person object in the form in editing mode.
1: @ model Person
html>
head>
Title> edit personnel information </title>
head>
body>
8: @using (Html.BeginForm())
10: <div>@Html.LabelFor(m=>m.Name)</div>
div>@Html.EditorFor(m=>m.Name)</div>
13: <div>@Html.LabelFor(m=>m.Gender)</div>
div>@Html.EditorFor(m => m.Gender)</div>
16: <div>@Html.LabelFor(m=>m.Age)</div>
div>@Html.EditorFor(m => m.Age)</div>
19: <input type = "submit" value = "save"/>
21: </body>
html>
After the program is run directly, a page for editing the basic information of the person will be displayed. If we enter illegal data and submit it, the verification information is displayed as shown in Figure 1.
Ii. Use the ValidationAttribute feature
Defining the verification logic and business logic for input parameters in the Action method is not a recommended programming method. In most cases, the same data type has the same verification rules in different application scenarios. If we can associate the verification rules with the data type, with the framework itself to implement data verification, developers can focus more on the implementation of business logic. In fact, this is also the default programming method supported by the Model verification system of ASP. net mvc. When defining a data type, you can apply the ValidationAttribute feature to the type and its data members to define the default verification rules.
The "System. ComponentModel. DataAnnotations" namespace defines a series of specific ValidationAttribute feature types, most of which can be directly applied to a property of a custom data type to verify the target data member. These predefined verification features are not the focus of this chapter. We will give a general introduction to them in the next section.
General verification can be done through the predefined ValidationAttribute features listed above, but in many cases we need to solve some special verification by creating custom ValidationAttribute features. For example, in the verification of the Person object in the example above, we require that the Gender attribute specify one of the two Gender values to indicate Gender: "M/m" and "F/f, this verification has to be implemented through the custom ValidationAttribute feature.
For verification rules such as "a value must be within the specified range", we define a DomainAttribute feature. As shown in the following code snippet, DomainAttribute has an IEnumerable <string> type read-only attribute Values that provides a list of valid Values, which are initialized in the constructor. The specific verification implementation is in the overwritten IsValid method. If the value to be verified is in this list, the verification is successful and True is returned. To provide a friendly error message, we have rewritten the FormatErrorMessage method.
1: [AttributeUsage (AttributeTargets. Property | AttributeTargets. Field, AllowMultiple = false)]
3: {
string> Values { get; private set; }
5:
7: {
8: this.Values = new string[] { value };
10:
12: {
13: this.Values = values;
15:
17: {
19: {
20: return true;
22: return this.Values.Any(item => value.ToString() == item);
24:
26: {
string.Format("'{0}'",value)).ToArray();
28: return string.Format(base.ErrorMessageString, name,string.Join(",", values));
30: }
Because ASP. net mvc automatically extracts the ValidationAttribute feature of the application on the target parameter type or data member during parameter binding, and verifies the provided data by using them, therefore, we no longer need to perform verification in the Action method as shown in the preceding example, you only need to apply the ValidationAttribute feature when defining the parameter type Person to associate the verification rules used with the corresponding data members. The following is a Person type definition that applies the ValidationAttribute attribute to attribute members. The requiredattri feature is applied to all three attributes to define them as required data members, in Gender and Age attributes, the DomainAttribute and RangeAttribute attributes are applied to limit the range of valid attribute values.
1: public class Person
3: [DisplayName ("name")]
5: public string Name { get; set; }
6:
8: [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources))]
10: public string Gender { get; set; }
11:
13: [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources))]
15: public int? Age { get; set; }
The error messages used by the three ValidationAttribute features are defined in the default resource file of the project (we can create this resource file by following these steps: Right-click the project in Solution Exploror, select "properties" in the context menu to open the "Project Properties" Object box. Finally, select the "resource" Tab in the dialog box and click the link on the page to create a resource file.) For details, see Definition 2.
Because ASP. net mvc will automatically extract the ValidationAttribute feature of the application on the binding parameter type to implement automatic verification of the bound parameter, so we do not need to manually verify the parameter in the specific Action method. As shown in the following code snippet, The Validate method is not explicitly called in the Action Method Index, however, after you run the program and submit the form with invalid input data, you will still get the output result shown in 1.
1: public class HomeController: Controller
3: // other members
5: public ActionResult Index(Person person)
7: if (!ModelState.IsValid)
9: return View(person);
11: else
13: return Content ("Verification of input data ");
15: }
2: {
3: IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
2: {
4: public string Name { get; set; }
5:
7: public string Gender { get; set; }
8:
10: public int? Age { get; set; }
11:
12: public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
14: Person person = validationContext.ObjectInstance as Person;
16: {
17: yield break;
19: if(string.IsNullOrEmpty(person.Name))
21: yield return new ValidationResult ("'name' is a required field", new string [] {"Name "});
23:
25: {
26: yield return new ValidationResult ("'gender' is a required field", new string [] {"Gender "});
28: else if (!new string[]{"M","F"}.Any(g=>string.Compare(person.Gender,g, true) == 0))
30: yield return new ValidationResult ("the valid 'gender' must be one of 'M', 'F'", new string [] {"Gender "});
32:
34: {
35: yield return new ValidationResult ("'age' is a required field", new string [] {"Age "});
37: else if (person.Age > 25 || person.Age < 18)
39: yield return new ValidationResult ("'age' must be between 18 and 25 years old", new string [] {"Age "});
41: }
2: {
3: string Error { get; }
4: string this[string columnName] { get; }
1: public class Person : IDataErrorInfo
3: [DisplayName ("name")]
4: public string Name { get; set; }
5:
7: public string Gender { get; set; }
8:
10: public int? Age { get; set; }
11:
13: public string Error { get; private set; }
14:
16: {
18: {
20: {
22: {
24: {
25: return "'name' is a required field ";
27: return null;
29: case "Gender":
31: if (string.IsNullOrEmpty(this.Gender))
33: return "'gender' is a required field ";
35: else if (!new string[] { "M", "F" }.Any(g => string.Compare(this.Gender, g, true) == 0))
37: return "'gender 'must be 'M', one of 'F ";
39: return null;
41: case "Age":
43: if (null == this.Age)
45: return "'age' is a required field ";
47: else if (this.Age > 25 || this.Age < 18)
49: return "'age' must be between 18 and 25 years old ";
51: return null;
53: default: return null;
55: }
57: }
58: }