if (! Modelstate.isvalid) { //todo model validation failed to do}
The code above, whether in traditional ASP. NET or New generation ASP. NET core, is to verify that the state of the model is legitimate, and if the value of the IsValid property is true, the validation succeeds. This kind of code is generally written in the first place in the action method, and if you write such a judgment in each action increases our workload and the repetition, in this article we will discuss how to automate model validation.
To implement this function, you first need to define a actionfilter
public class validatemodelstateattribute:microsoft.aspnetcore.mvc.filters.actionfilterattribute{Public override void OnActionExecuting (ActionExecutingContext context) { if (!context. Modelstate.isvalid) { list<string> errorlist = new list<string> (); foreach (var modelstate in context. Modelstate.values) { foreach (var error in modelstate.errors) { errorlist.add (Error). errormessage); } } Context. Result = new Jsonresult (New {success = false, message = Errorlist});}}
Modifying the Startup class
public void Configureservices (iservicecollection services) { services. ADDMVC (options = options. Filters.add (typeof (Validatemodelstateattribute));} );
Automatic model validation is achieved. Take an experiment:
public class user{ [Required] [emailaddress] public string Email {get; set;} [Required] public string Name {get; set;}}
[Httppost]public iactionresult Insert (user user) { return Json (user);}
Is it a bit of an AOP idea?
Original address: http://www.talkingdotnet.com/validate-model-state-automatically-asp-net-core-2-0/
Validate Model state automatically in ASP. NET Core 2.0