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/