【问题标题】:asp net core web api custom model validationasp net core web api自定义模型验证
【发布时间】:2021-01-01 06:40:21
【问题描述】:

Asp net core web API,我正在尝试为模型验证器返回自定义响应。但是ValidateModelFilter在需要字段时没有调用,不在请求中。

ValidateModelFilter.cs

public class ValidateModelFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
             var response = new Model
             {
                 error = context.ModelState.ToString()
             };
             context.Result = new BadRequestObjectResult(response);
         }
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => options.Filters.Add(typeof(ValidateModelFilter)));
}

我收到这样的回复

{
  "errors": {
    "Firstname": [
      "The Firstname field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|e6752549-4142e91f1074e978."
}

我想返回类似的响应

{
"error": "The Firstname field is required."
}

【问题讨论】:

    标签: asp.net-core-webapi


    【解决方案1】:

    该链接显示了我们必须如何禁用返回 400 错误并短路管道的默认模型绑定异常过滤器。只有这样我们的自定义 ActionFilterAttribute 中的 OnActionExecuting 方法才会真正被执行。然后一切都按预期工作。

    https://stackoverflow.com/a/51522487/14924779

    【讨论】:

      猜你喜欢
      • 2019-03-26
      • 1970-01-01
      • 2019-01-12
      • 2018-08-24
      • 1970-01-01
      • 2018-03-15
      • 2020-08-30
      • 1970-01-01
      相关资源
      最近更新 更多