Validate Model state automatically in ASP. NET Core 2.0

Source: Internet
Author: User

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

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.