【问题标题】:ASP.NET Core Action Filter Doesn't Get Called未调用 ASP.NET Core 操作筛选器
【发布时间】:2019-07-29 17:58:00
【问题描述】:

我有一个 ASP.NET Core API (.Net Core 2.1),我使用这篇文章实现了一个动作过滤器

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#action-filters

在我的模型中,我使用数据注释来验证模型,并在我的控制器中为动作添加了 ValidateModel 属性。

    [HttpPost("CreateShipment")]
    [ValidateModel]
    public IActionResult CreateShipment([FromBody] CreateShipmentRequest request)
    {
         if (ModelState.IsValid)
         {
            //Do something
         }
         return Ok();
    }

我使用 Postman 对此进行了测试,并且仅当模型有效时才会调用我的动作过滤器。如果我的请求缺少必填字段或某些值超出范围,则不会调用 Action Filter。相反,我收到一个 400 错误请求,响应中包含模型状态。

我实现了动作过滤器,因为我想自定义我的模型验证错误。我的理解是在模型绑定时调用动作过滤器。谁能帮我弄清楚为什么会发生这种情况以及如何让动作过滤器工作?

更新:我在发布问题 2 秒后找到了解决方案,下面发布的链接 @Silvermind 也是很好的信息。

我将以下行添加到我的 Startup.cs

services.Configure<ApiBehaviorOptions>(options =>
{
     options.SuppressModelStateInvalidFilter = true;
});

Microsoft 网站上有详细的记录。 https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#automatic-http-400-responses

【问题讨论】:

  • 自 .net core 2.1 起,[ApiController] 属性会自动放置在控制器上。那会自动做一些事情;删除它可以解决这个问题。看看这篇文章了解更多信息:Exploring the ApiControllerAttribute and its features for ASP.NET Core MVC 2.1
  • @Silvermind 感谢您的帮助。在您发布此内容之前,我实际上已经找到了自己的解决方案。我在我的 Startup.cs 中的 ConfigureServices() services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); 添加了以下内容
  • 这是一个不错的解决方案。我建议您将其作为答案而不是将其添加到您的问题中并接受您自己的答案。

标签: c# .net asp.net-core actionfilterattribute custom-action-filter


【解决方案1】:

在 Startup.cs 中添加以下行,ConfigureServices() 方法解决了该问题。事实证明,.Net Core 默认启用了自动 400 响应。如果要添加自定义操作过滤器,则需要在启动时设置这些选项。

services.Configure<ApiBehaviorOptions>(options =>
{
      options.SuppressModelStateInvalidFilter = true;
});

Microsoft 网站上有详细记录:

https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#automatic-http-400-responses

【讨论】:

    【解决方案2】:

    [ApiController] 属性自动执行模型验证并触发 404 的 HTTP 响应,在 .Net Core 3.0 中,您可以链接到新的 AddControllers() 以抑制此功能:

    services.AddControllers()
                    .ConfigureApiBehaviorOptions(options =>
                    {
                        options.SuppressModelStateInvalidFilter = true;
                    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-13
      • 2018-03-29
      • 2014-06-30
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      相关资源
      最近更新 更多