参考:
关闭默认模型验证过滤器
[ApiController] 默认自带有400模型验证,且优先级比较高,如果需要自定义模型验证,则需要先关闭默认的模型验证
在StartUp.cs 中的MVC服务配置修改
#region MVC
services.AddMvc(o =>
{
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.ConfigureApiBehaviorOptions(o =>
{
o.SuppressModelStateInvalidFilter = true;
});
#endregion
首先定义统一输出的格式为
{
code:
errors:[
filed:
message:
]
}
添加自定义模型验证DTO
public class ErrorResultDTO
{
/// <summary>
/// 参数领域
/// </summary>
public string Field { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string Message { get; set; }
}
添加过滤器
过滤器继承自:ActionFilterAttribute, IActionFilter
public class ModelActionFiter :ActionFilterAttribute, IActionFilter
{
public ModelActionFiter()
{
}
public override void OnActionExecuted(ActionExecutedContext context)
{
}
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
List<ErrorResultDTO> errorResults = new List<ErrorResultDTO>();
foreach (var item in context.ModelState)
{
var result = new ErrorResultDTO
{
Field = item.Key,
Msg = "",
};
foreach (var error in item.Value.Errors)
{
if (!string.IsNullOrEmpty(result.Msg))
{
result.Msg += '|';
}
result.Msg += error.ErrorMessage;
}
errorResults.Add(result);
}
context.Result = new BadRequestObjectResult(new
{
Code = StatusCodes.Status400BadRequest,
Errors = errorResults
});
}
}
}
将写的过滤器注册到全局
services.AddMvc(o =>
{
o.Filters.Add(new ModelActionFiter());
})
结果测试
原文:https://www.cnblogs.com/minskiter/p/11601873.html