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