Validate Model State automatically in ASP.NET Core 2.0
2018-02-13 20:22
926 查看
if (!ModelState.IsValid) { //TODO 模型验证失败需要做的事情 }
上面的代码不管是在传统的ASP.NET还是新一代ASP.NET Core中都是为了验证模型的状态是否合法,如果IsValid属性的值为True,则验证成功。这样的代码一般我们会写在Action方法中的最开始处,如果在每个Action中都写这样的判断就会增加我们的工作量和以及存在重复性,在这篇文章中将讨论如何自动进行模型验证。
要实现这个功能首先需要定义一个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 }); } } }
修改启动类
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(typeof(ValidateModelStateAttribute)); }); }
自动进行模型验证就实现了。走个实验:
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); }
是不是有点AOP的意思呢?
原文地址:http://www.talkingdotnet.com/validate-model-state-automatically-asp-net-core-2-0/
相关文章推荐
- ASP.NET Core 2.0 in Docker on Windows Containers
- [转]An introduction to OAuth 2.0 using Facebook in ASP.NET Core
- [转]Session and application state in ASP.NET Core
- asp.net mvc 2.0 validate model
- Speed Up Your Site with the Improved View State in ASP.NET 2.0
- 获取Action的ModelState中所有验证信息的方式(Asp.net MVC)
- Automatically Printing Crystal Reports in ASP.NET
- ASP.NET Core 2.0 : 四. _Layout与_ViewStart
- Asp.net MVC Model设置为string类型时报错:Illegal characters in path
- ASP.NET Core 2.0 MVC - 获取当前登录用户信息
- Using ConnectionStrings in ASP.NET 2.0
- ASP.NET Core 2.0系列学习笔记-ADO.NET-MSSQLServerHelper
- Dependency Injection in ASP.NET Core
- [转载]Encrypting Configuration Information in ASP.NET 2.0 Applications
- asp.net core 2.0 webapi集成signalr
- Validate Image Type Using Image GUID in ASP.NET(Asp.Net中使用图片GUID验证图片类型)
- 从头编写 asp.net core 2.0 web api 基础框架 (3)
- 从头编写 asp.net core 2.0 web api 基础框架 (3)
- Display Hierarchical Data with TreeView in ASP.NET 2.0
- Create an ASP.NET Core web app in Visual Studio Code