ASP. NET WEB API Custom model Check Filter

Source: Internet
Author: User

When exposing the Web interface externally, it is common security common sense to validate the model, and the common writing is to judge Modelstate.isvalid in the controller and take the registered user API as an example.

Model:

 Public classregistercustomermodel{[Required (ErrorMessage="the name cannot be empty")] [Stringlength (Ten, errormessage ="name cannot be longer than 10 characters")]         Public stringName {Get;Set; } [Required (ErrorMessage="The phone cannot be empty")] [RegularExpression (@"^1[34578]\d{9}$", errormessage ="phone number is not formatted correctly")]         Public stringPhone {Get;Set; } [Required (ErrorMessage="The password cannot be empty")] [Stringlength ( -, errormessage ="password length cannot exceed 48 characters")]         Public stringPassword {Get;Set; }}

Error message code for print check failure:

 Public Static classmodelstateextension { Public Static stringToerrormessage ( Thismodelstatedictionary modelstatedictionary) {            varStringBuilder =NewStringBuilder (); foreach(varValueinchmodelstatedictionary.values) {foreach(varErrorinchvalue. Errors) {stringbuilder.appendline (error.                ErrorMessage); }            }            returnstringbuilder.tostring (); }   }

Controller:

 Publicresponseprotocol Register (Registercustomermodel registercustomermodel) {if(!modelstate.isvalid) {return NewResponseprotocol ((int) Responseresultenum.validateerror, Modelstate.toerrormessage (),string.            Empty); } Customer Customer=NewCustomer {Name=Registercustomermodel.name, Phone=Registercustomermodel.phone, Weixinno=Registercustomermodel.weixinno, Company=Registercustomermodel.company, UpdateTime=DateTime.Now};            _customerservice.add (customer); return NewResponseprotocol ((int) Responseresultenum.success,"Registration Successful",string.    Empty); }

The above notation is in the controller in the verification, the disadvantage is that each need to verify the controller to write once, in order to eliminate duplication, you can officer code written to the global filter, by the filter for unified model validation, modified code:

 Public classValidationmodelfilter:actionfilterattribute { Public Override voidonactionexecuting (Httpactioncontext actioncontext) {//The Get method does not validate the model            if(actioncontext.request.method.method=="GET")            {                return; }            if(!actionContext.ModelState.IsValid) {varError = Jsonconvert.serializeobject (NewResponseprotocol () {Code=(int) Responseresultenum.validateerror, Message=actionContext.ModelState.ToErrorMessage (), Data=string.                Empty}); varHttpresponsemessage =NewHttpresponsemessage {Content=Newstringcontent (Error)}; HttpResponseMessage.Content.Headers.ContentType=NewMediatypeheadervalue ("Application/json"); Actioncontext.response=Httpresponsemessage; }        }    }

Then register with the global Filter (webapiconfig): CONFIG. Filters.add (New Validationmodelfilter ());

ASP. NET WEB API Custom model Check Filter

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.