1、关闭默认模型验证过滤器
[ApiController] 默认自带有400模型验证,且优先级比较高,如果需要自定义模型验证,则需要先关闭默认的模型验证
在StartUp.cs 中的MVC服务配置修改
services.AddControllers(options => { options.Filters.Add(new AuthorizeFilter()); //授权过滤器 options.Filters.Add(new ModelActionFilter()); //注册全全局模型验证过滤器 }) .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; //抑制系统自带模型验证 }) .AddControllersAsServices();
2、添加自定义模型验证
public class ErrorResult { /// <summary> /// 参数领域 /// </summary> public string Field { get; set; } /// <summary> /// 错误信息 /// </summary> public string Message { get; set; } }
3、添加过滤器
过滤器继承自:ActionFilterAttribute, IActionFilter
public class ModelActionFilter:ActionFilterAttribute,IActionFilter { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { var errorResults=new List<ErrorResult>(); foreach (var item in context.ModelState) { var result=new ErrorResult() { Field = item.Key, }; foreach (var error in item.Value.Errors) { if (!string.IsNullOrEmpty(result.Message)) { result.Message += "|"; } result.Message += error.ErrorMessage; } errorResults.Add(result); } context.Result=new BadRequestObjectResult(new { Code=StatusCodes.Status400BadRequest, Errors=errorResults }); } } }