Four authentication programming methods of ASP. net mvc, asp. netmvc

Source: Internet
Author: User
Tags see definition

Four authentication programming methods of ASP. net mvc, asp. netmvc

We can use four different programming modes to verify the binding parameters.

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.

Public class Person {[DisplayName ("Name")] public string Name {get; set;} [DisplayName ("Gender")] public string Gender {get; set ;} [DisplayName ("Age")] public int? Age {get; set ;}}

Next we define the next HomeController. In the Action method Index of the GET request, we create a Person object and render it as a Model in the corresponding View. Another Index method that supports POST requests has a Person-type parameter. In this Action method, we call the Validate method to verify this input parameter. If the verification succeeds (the ModeState. IsValid attribute returns True), a ContentResult with the content "input data verified" is returned. Otherwise, this parameter is displayed as a Model in the corresponding View.

Public class HomeController: Controller {[HttpGet] public ActionResult Index () {return View (new Person ();} [HttpPost] public ActionResult Index (Person person Person) {Validate (person); if (! ModelState. isValid) {return View (person);} else {return Content ("input data verified") ;}} private void Validate (Person person) {if (string. isNullOrEmpty (person. name) {ModelState. addModelError ("Name", "'name' is a required field");} if (string. isNullOrEmpty (person. gender) {ModelState. addModelError ("Gender", "'gender' is a required field");} else if (! New string [] {"M", "F "}. any (g => string. compare (person. gender, g, true) = 0) {ModelState. addModelError ("Gender", "valid 'gender' must be 'M', one of 'F'");} if (null = person. age) {ModelState. addModelError ("Age", "'age' is a required field");} else if (person. age> 25 | person. age <18) {ModelState. addModelError ("Age", "valid 'age' must be between 18 and 25 years old ");}}}

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.

@ Model Person 

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.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,  AllowMultiple = false)] public class DomainAttribute : ValidationAttribute {   public IEnumerable<string> Values { get; private set; }    public DomainAttribute(string value)   {     this.Values = new string[] { value };   }    public DomainAttribute(params string[] values)   {     this.Values = values;   }    public override bool IsValid(object value)   {     if (null == value)     {       return true;     }     return this.Values.Any(item => value.ToString() == item);   }    public override string FormatErrorMessage(string name)   {     string[] values = this.Values.Select(value => string.Format("'{0}'", value)).ToArray();     return string.Format(base.ErrorMessageString, name,string.Join(",",  values));   } } 

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.

Public class Person {[DisplayName ("Name")] [Required (ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof (Resources)] public string Name {get; set ;} [DisplayName ("gender")] [Required (ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof (Resources)] [Domain ("M", "F", "m ", "f", ErrorMessageResourceName = "Domain", ErrorMessageResourceType = typeof (Resources)] pu Blic string Gender {get; set;} [DisplayName ("Age")] [Required (ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof (Resources)] [Range (18, 25, ErrorMessageResourceName = "Range", ErrorMessageResourceType = typeof (Resources)] 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.

Public class HomeController: Controller {// other member [HttpPost] public ActionResult Index (Person person) {if (! ModelState. IsValid) {return View (person);} else {return Content ("input data verified ");}}}

Iii. Implement the IValidatableObject interface for Data Types

In addition to defining the validation rules directly on the Data Type through the ValidationAttribute feature and enabling ASP. in addition to parameter verification during parameter binding, we can also define the verification operation in the data type. Since we directly implement the verification operation on the data type, it means that the corresponding data object has the "self-verification" capability, we will refer to these data types as "self-verification type ". These self-verification types implement the IValidatableObject interface with the following definitions, which are defined under the namespace "System. ComponentModel. DataAnnotations.

public interface IValidatableObject {   IEnumerable<ValidationResult> Validate( ValidationContext validationContext); } 

As shown in the code snippet above, the IValidatableObject interface has a unique method Validate, which implements self-verification in this method. For the data type Person defined in the example above, we can define it as a self-validation type in the following form.

Public class Person: IValidatableObject {[DisplayName ("Name")] public string Name {get; set;} [DisplayName ("Gender")] public string Gender {get; set ;} [DisplayName ("Age")] public int? Age {get; set;} public IEnumerable <ValidationResult> Validate (ValidationContext validationContext) {Person person = validationContext. objectInstance as Person; if (null = person) {yield break;} if (string. isNullOrEmpty (person. name) {yield return new ValidationResult ("'name' is a required field", new string [] {"Name"});} if (string. isNullOrEmpty (person. gender) {yield return new ValidationResult ("'gender 'Is a required field ", new string [] {" Gender "});} else if (! New string [] {"M", "F "}. any (g => string. compare (person. gender, g, true) = 0) {yield return new ValidationResult ("the valid 'gender' must be one of 'M' and 'f ", new string [] {"Gender"});} if (null = person. age) {yield return new ValidationResult ("'age' is a required field", new string [] {"Age"});} else if (person. age> 25 | person. age <18) {yield return new ValidationResult ("'age' must be between 18 and 25 years old", new string [] {"Age "});}}}

As shown in the code snippet above, the IValidatableObject interface is implemented for the Person type. In the implemented Validate method, we obtain the verified Person object from the verification context and verify its attribute members one by one. If the data member does not pass the verification, an error message and a data member name (attribute name) are encapsulated through a ValidationResult object. This method returns a set of ValidationResult element types. Without making any changes to other code, we can directly run the program and submit the form with invalid data input. The output result shown in 1 is still displayed.

Iv. Implement the IDataErrorInfo interface for Data Types

The above section describes how to implement the IValidatableObject interface of the Data Type and define the verification logic in the implemented Validate method. Such a type can be ASP.. net mvc, which automatically calls this method to verify the bound data object. If we implement the IDataErrorInfo interface for the data type, similar automated verification results can also be achieved.

The IDataErrorInfo interface is defined in the "System. ComponentModel" namespace. It provides a standard method for customizing error information. As shown in the following code snippet, IDataErrorInfo has two members. The read-only attribute Error is used to obtain the Error message based on itself, and the read-only index is used to return the Error message of the specified data member.

public interface IDataErrorInfo {   string Error { get; }   string this[string columnName] { get; } } 

This is also for the instance demonstrated above. Now we have redefined the data type Person to be verified. As shown in the following code snippet, we have implemented the IDataErrorInfo interface for Person. In the implemented index, we regard the index parameter columnName as the attribute name, and verify the corresponding attribute members according to the above rules, if the verification fails, the corresponding error message is returned. Without making any changes to other code, we can directly run the program and submit the form with invalid data input. The output result shown in 1 is still displayed.

Public class Person: IDataErrorInfo {[DisplayName ("Name")] public string Name {get; set;} [DisplayName ("Gender")] public string Gender {get; set ;} [DisplayName ("Age")] public int? Age {get; set;} [ScaffoldColumn (false)] public string Error {get; private set;} public string this [string columnName] {get {switch (columnName) {case "Name": {if (string. isNullOrEmpty (this. name) {return "'name' is a required field";} return null;} case "Gender": {if (string. isNullOrEmpty (this. gender) {return "'gender' is a required field";} else if (! New string [] {"M", "F "}. any (g => string. compare (this. gender, g, true) = 0) {return "'gender 'must be one of 'M' and 'f'";} return null;} case "Age ": {if (null = this. age) {return "'age' is a required field";} else if (this. age> 25 | this. age <18) {return "'age' must be between 18 and 25 years old";} return null;} default: return null ;}}}}

The above is the implementation code for binding parameter verification using four different programming modes, hoping to help you learn.

Related Article

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.