fluentvalidation validation of ASP. NET Web API

Source: Internet
Author: User
Tags getmessage

Recently in the Web API, the use of streaming authentication, simply say this streaming authentication.

First we define a filter, as follows

 public class ValidateResponseFilterAttribute : ActionFilterAttribute     {        public override void  OnActionExecuting (System.web.http.controllers.httpactioncontext actioncontext)          {            if  (! ActionContext.ModelState.IsValid)             {                 // actioncontext.modelstate.keys                 actioncontext.response = actioncontext.request.createerrorresponse ( Httpstatuscode.badrequest, actioncontext.modelstate);             }       &nbsP;}     }

Overrides the action execution method and returns 500error to the client if the request model has an exception.

What do we do next, define a Basecontroller

[validateresponsefilter]    public class basecontroller :  apicontroller    {        protected  Httpresponsemessage createsystemerrorresponse (string errormsg)          {            return  Request.createresponse<object> (                    new                    {                        issuc = false,                         errormsg = errormsg                    });        }         Protected httpresponsemessage createerrorresponse (String responsecode, type type  = null, httpstatuscode statuscode = httpstatuscode.ok)          {            return  Request.createresponse<object> (statuscode,                    new                    {                        issuc =  false,                        errormsg = messagereshelper.getmessage (Type != null ? type. Name : this. GetType (). Name, responsecode)                     });        }         protected httpresponsemessage createsucresponse (String responseCode  =  "")         {             if  (String. IsNullOrEmpty (responsecode))             {                 return  Request.createresponse<object> (NEW&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;            {                         issuc = true                    });             }             return Request.CreateResponse< Object> (                    new                    {                        IsSuc = true,                        errormsg =  Messagereshelper.getmessage (this. GetType (). Name, responsecode)                     });         }}

On Basecontroller We mark the above attribute and verify that it is not intercepted by the request.

Now let's look at the definition of request

public class customervalidaterequest :  ivalidatableobject{    private readonly ivalidator _validator;     public customervalidaterequest ()     {         _validator = new customervalidaterequestvalidator ();    }     public string Email { get; set; }     Public string password { get; set; }    public string  ValidateCode { get; set; }    public IEnumerable< Validationresult> validate (Validationcontext validationcontext)     {         return _validator. Validate (This). Tovalidationresult ();     }} 

After the

Request is defined, we write the method at the bottom to get the result of the validation. Now let's look at our validator

public class customervalidaterequestvalidator : abstractvalidator< Customervalidaterequest>{    public customervalidaterequestvalidator ()      {        rulefor (dto => dto. Email). Notnull (). Notempty ();         rulefor (dto => dto. Password). Notnull (). Notempty ();         rulefor (dto => dto. Validatecode). Notnull (). Notempty (). Length (webappsettings.validatecodelength);         when (dto =>  !string. Isnullorwhitespace (DTO. Email),  ()  =>        {             rulefor (C => c.email). Matches (@ "^ [\w-\.] +) @ ((\[[0-9]{1,3}\. [0-9] {1,3}\. [0-9] {1,3}\.) | ([\w-]+\.) +)) ([a-za-z]{2,4}| [0-9] {1,3}) (\]?) $ ");         });     }} 

Here is the logic that we want to verify, which verifies the most basic non-null, length, and can also validate the regular. The rulefor returned here is the following interface type

Public irulebuilderinitial<t, Tproperty> rulefor<tproperty> (expression<func<t, TProperty>> Expression

The interface inherits the Irulebuilder interface

Public interface Irulebuilderinitial<t, out tproperty>: Ifluentinterface, Irulebuilder<t, Tproperty>, Iconfigurable<propertyrule, Irulebuilderinitial<t, tproperty>>

Irulebuild has many extension methods in the Defaultvalidatorextensions class, as follows

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/82/B5/wKiom1dex4vgC2RPAADiaPwWg-Q515.png "title=" Qq20160613224249.png "alt=" Wkiom1dex4vgc2rpaadiapwwg-q515.png "/> is simply too much, verify credit cards, mailboxes, comparison size, area, not equal to and so on, of course you can also expand some of them out.

Let's take a look at the effect with Google DHC

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/82/B5/wKiom1deyIXRH6aMAAA64QyvxHc413.png "title=" Qq20160613225136.png "alt=" Wkiom1deyixrh6amaaa64qyvxhc413.png "/>

If nothing is passed, it is validated against the validation rules above.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/82/B4/wKioL1deye_wOztiAAA8hgpHD3A410.png "title=" Qq20160613225255.png "alt=" Wkiol1deye_woztiaaa8hgphd3a410.png "/>

If an email is sent, it verifies that the email is correct.

Finally, remember to add the following code to the Globle.asax.cs

Dataannotationsmodelvalidatorprovider.addimplicitrequiredattributeforvaluetypes = false; MODELVALIDATORPROVIDERS.PROVIDERS.ADD (New Fluentvalidationmodelvalidatorprovider (New Attributedvalidatorfactory ( ))); Validatoroptions.cascademode = cascademode.stoponfirstfailure; Fluentvalidationmodelvalidatorprovider.configure ();

All right, here we go today, for more details, please read the following blog post.

https://chsakell.com/2015/01/17/web-api-powerful-custom-model-validation-with-fluentvalidation/

This article is from the "Technology Creation value" blog, please be sure to keep this source http://leelei.blog.51cto.com/856755/1788944

fluentvalidation validation of ASP. NET Web API

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.