Several Methods for ASP. net mvc background parameter verification, asp. netmvc

Source: Internet
Author: User

Several Methods for ASP. net mvc background parameter verification, asp. netmvc

Preface

Parameter verification is a common problem. Both the frontend and backend must verify user input to ensure the correctness of system data. For the web, some people may naturally want to verify the code on the front-end, but this is a very wrong practice. The front-end code is transparent to users, people with a little technical skills can bypass this verification and directly submit data to the background. Whether it is an interface submitted by a front-end webpage or an interface provided to an external user, parameter verification is everywhere and is also essential. In short, all user input is untrusted.

Parameter verification can be performed in many ways. The following uses mvc as an example to list several common verification methods. assume there is a user registration method.

[HttpPost]public ActionResult Register(RegisterInfo info)

1. if-if 

If (string. isNullOrEmpty (info. userName) {return FailJson ("UserName cannot be blank");} if (string. isNullOrEmpty (info. password) {return FailJson ("the user Password cannot be blank ")}

Verify the parameters one by one. This method is the most crude, but it was indeed used in WebForm. The method with few parameters is fine. if there are more than one parameter, you need to write n more if-if statements, which is quite tedious. More importantly, this part of the judgment cannot be reused. The other method is to make such judgments.

2. DataAnnotation

Mvc provides DataAnnotation to verify the Model of Action. In the end, DataAnnotation inherits the characteristics of ValidationAttribute, such as RangeAttribute and RequiredAttribute. The virtual method IsValid of ValidationAttribute is used to determine whether the marked object conforms to the current rule. Asp.net mvc obtains the ValidationAttribute of the tag through reflection during model binding, and CALLS IsValid to determine whether the current parameter complies with the rule. If the verification fails, it also collects error information, this is why we can use ModelState in Action. isValid checks whether Model verification is successful, and obtains the cause of verification failure information through ModelState. For example:

Public class RegisterInfo {[Required (ErrorMessage = "UserName cannot be blank")] public string UserName {get; set;} [Required (ErrorMessage = "password cannot be blank")] public string Password {get; set ;}}

In fact, you can refer to the implementation principle of mvc to implement this process on webform. The advantages of this method are very elegant and flexible. If multiple actions share a Model parameter, you only need to write it in one place, the key is that it makes our code look very concise.

However, this method also has disadvantages. Generally, our project may have many interfaces, such as dozens of interfaces. Some interfaces have only two or three parameters, defining a class packaging parameter for each interface is a luxury, and it is also a headache to name this class.

3. DataAnnotation can also be marked on Parameters

The buteusage of the verification feature shows that it can be marked not only on attributes and fields, but also on parameters. In other words, we can also write:

Public ActionResult Register ([Required (ErrorMessage = "userName cannot be blank")] string userName, [Required (ErrorMessage = "password cannot be blank")] string password)

This is also OK, but it is obvious that it is difficult to write method parameters, especially when there are multiple parameters or there are multiple verification rules for parameters.

Iv. Customize ValidateAttribute

We know that the filter can be used to perform some processing before the mvc Action is executed, such as identity authentication and authorization. Similarly, the parameter can also be verified here. FilterAttribute is a common filter that allows us to perform operations before and after the Action is executed. Here we want to verify the parameter before the Action. If the verification fails, it will not be executed.

Define a BaseValidateAttribute base class as follows:

public class BaseValidateAttribute : FilterAttribute{  protected virtual void HandleError(ActionExecutingContext context)  {    for (int i = ValidateHandlerProviders.Handlers.Count; i > 0; i--)    {      ValidateHandlerProviders.Handlers[i - 1].Handle(context);      if (context.Result != null)      {        break;      }    }  }} 

HandleError is used to process results when verification fails. Here ValidateHandlerProviders mentioned IValidateHandler to process results, which can be registered externally. IValidateHandler is defined as follows:

public interface IValidateHandler{  void Handle(ActionExecutingContext context);} 

ValidateHandlerProviders is defined as follows. It has a default processor.

public class ValidateHandlerProviders{  public static List<IValidateHandler> Handlers { get; private set; }   static ValidateHandlerProviders()  {    Handlers = new List<IValidateHandler>()    {      new DefaultValidateHandler()    };  }   public static void Register(IValidateHandler handler)  {    Handlers.Add(handler);  }}   

This is intended because we may have a lot of specific ValidateAttribute. We can separate this module and leave the final processing process to external decisions, for example, we can define a processor in a project:

Public class StanderValidateHandler: IValidateHandler {public void Handle (ActionExecutingContext filterContext) {filterContext. result = new StanderJsonResult () {Result = FastStatnderResult. fail ("parameter Verification Failed", 555 )};}}

Then register when the application starts: ValidateHandlerProviders. Handlers. Add (new StanderValidateHandler ());

Here are two examples:

ValidateNullttribute:

public class ValidateNullAttribute : BaseValidateAttribute, IActionFilter{  public bool ValidateEmpty { get; set; }   public string Parameter { get; set; }   public ValidateNullAttribute(string parameter, bool validateEmpty = false)  {    ValidateEmpty = validateEmpty;    Parameter = parameter;  }   public void OnActionExecuting(ActionExecutingContext filterContext)  {    string[] validates = Parameter.Split(',');    foreach (var p in validates)    {      string value = filterContext.HttpContext.Request[p];      if(ValidateEmpty)      {        if (string.IsNullOrEmpty(value))        {          base.HandleError(filterContext);        }      }      else      {        if (value == null)        {          base.HandleError(filterContext);        }      }    }  }   public void OnActionExecuted(ActionExecutedContext filterContext)  {   }} 

ValidateRegexAttribute:

 public class ValidateRegexAttribute : BaseValidateAttribute, IActionFilter{  private Regex _regex;   public string Pattern { get; set; }   public string Parameter { get; set; }   public ValidateRegexAttribute(string parameter, string pattern)  {    _regex = new Regex(pattern);    Parameter = parameter;  }   public void OnActionExecuting(ActionExecutingContext filterContext)  {    string[] validates = Parameter.Split(',');    foreach (var p in validates)    {      string value = filterContext.HttpContext.Request[p];      if (!_regex.IsMatch(value))      {        base.HandleError(filterContext);      }    }  }  public void OnActionExecuted(ActionExecutedContext filterContext)  {   }} 

More verification can be done in the same way.

In this way, the above statement becomes:

[ValidateNull("userName,password")]public ActionResult Register(string userName, string password) 

In general, it seems to be OK. We can weigh the preceding DataAnnotation and choose to use it. here we can expand more useful information, such as error descriptions.

Summary

Of course, each method has its own shortcomings. This is based on the actual situation. We recommend that you use an object to wrap up too many parameters.

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.