其他分享
首页 > 其他分享> > .net5 WebAPI 参数验证 ModelValid

.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();
  };
});

标签:WebAPI,ModelState,errors,return,ModelValid,keyValue,context,new,net5
来源: https://www.cnblogs.com/ives/p/15693409.html