This problem has plagued me for a long time after the Action received a JSON string and then serialized the string as an entity, and then how to use MVC's own parameter Validation framework to validate the parameters. Some people may say that when invoking an interface, add a request header, set Contentype to Application/json, and the action method can accept JSON parameters with the entity. But that's not the situation I'm dealing with. All I need to do is accept the JSON string and serialize it to the entity. Do not for me why, I was so stubborn. Ha ha
Solution directly on the code, by adding an extension method to the controller to meet my needs, one thing to note is that when the controller calls the extension method, it is necessary to use this.xxx. Okay, on the code.
Extension methods:
usingSystem;usingSystem.Collections;usingSystem.Linq.Expressions;usingSYSTEM.WEB.MVC;namespacelyt.framework{ Public Static Partial classcontrollerextensions { Public Static BOOLValidatemodelextensions ( ThisController controller,Objectmodel) { returnValidatemodelextensions (Controller, model,NULL); } Private Static BOOLValidatemodelextensions ( ThisController controller,ObjectModelstringprefix =NULL) { if(model = =NULL) { Throw NewArgumentNullException ("Model"); } if(model isIEnumerable) { foreach(varIteminchModel asIEnumerable) {validatemodelbase (Controller, item, prefix); } } Else{validatemodelbase (Controller, model, prefix); } returnController. Modelstate.isvalid; } Private Static voidValidatemodelbase (Controller controller,ObjectModelstringprefix) {Modelmetadata metadata= ModelMetadataProviders.Current.GetMetadataForType (() =model, model. GetType ()); foreach(Modelvalidationresult ValidationresultinchModelvalidator.getmodelvalidator (metadata, controller. ControllerContext). Validate (NULL) ) {controller. Modelstate.addmodelerror (createsubpropertyname (prefix, validationresult.membername), validationresult.message); } } Private Static stringCreatesubpropertyname (stringPrefixstringPropertyName) { if(string.isnullorempty (prefix)) {returnPropertyName; } Else if(String.IsNullOrEmpty (PropertyName)) {returnprefix; } Else { returnPrefix +"."+PropertyName; } } }}View Code
Invocation Example:
PublicActionResult Validatemodeltest (stringJsonmodel) {List<PersonModel> list = jsonconvert.deserializeobject<list<personmodel>>(Jsonmodel); if( This. Validatemodelextensions (list)) {returnContent ("OK"); } Else { returnContent ("parameter Exception"); } }View Code
Get.
Now you can use it to achieve a variety of business needs.
How to use MVC parameters to validate a model after C # MVC enters the action method