利用InvalidModelStateResponseFactory
官网推荐做法 覆盖ModelState管理的默认行为
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = (context) =>
{
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (KeyValuePair<string, ModelStateEntry> keyValue in context.ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
if (errors.Any())
{
return new JsonResult(errors);
}
return new EmptyResult();
};
});