.net5 WebAPI 参数验证 ModelValid

利用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();
  };
});
上一篇:解决使用jenkins构建react项目失败


下一篇:Go 错误处理