Validate Model State maid in ASP. NET Core 2.0,

Source: Internet
Author: User

Validate Model State maid in ASP. NET Core 2.0,

If (! ModelState. IsValid) {// things to be done when TODO model verification fails}

The above code is used to verify whether the model status is valid in the traditional ASP. NET or the new-generation ASP. NET Core. If the IsValid attribute value is True, the verification is successful. Such code is generally written at the beginning of the Action method. If such a judgment is written in every Action, the workload and repetition will increase, this article will discuss how to automatically perform model verification.

To implement this function, you must first define an 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 });        }    }}

Modify startup class

public void ConfigureServices(IServiceCollection services){    services.AddMvc(options =>    {        options.Filters.Add(typeof(ValidateModelStateAttribute));    });}

Automatic model verification is implemented. 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);}

Does it mean something about AOP?

Address: http://www.talkingdotnet.com/validate-model-state-automatically-asp-net-core-2-0/

Related Article

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.