在 ASP.NET Core 中到达控制器之前拦截错误请求 [英] Intercept bad requests before reaching controller in ASP.NET Core

查看:40
本文介绍了在 ASP.NET Core 中到达控制器之前拦截错误请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果收到的请求是 BadRequest,我有一个应用逻辑,为此我创建了一个过滤器:

I have a logic to apply in case the request received is a BadRequest, to do this I have created a filter:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            // Apply logic
        }
    }
}

在启动中:

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

控制器:

[Route("api/[controller]")]
[ApiController]
public class VerifyController : ControllerBase
{
    [Route("test")]
    [HttpPost]
    [ValidateModel]
    public ActionResult<Guid> validationTest(PersonalInfo personalInfo)
    {
        return null;
    }
}

型号:

public class PersonalInfo
{
    public string FirstName { get; set; }
    [RegularExpression("\d{4}-?\d{2}-?\d{2}", ErrorMessage = "Date must be properly formatted according to ISO 8601")]
    public string BirthDate { get; set; }
}

问题是当我在行上放置一个断点时:

The thing is when I put a break point on the line:

if (!context.ModelState.IsValid)

只有当我发送的请求有效时,才会执行到这一行.如果我发送了一个错误的请求,为什么它没有通过过滤器?

execution reaches this line only if the request I send is valid. Why it is not passing the filter if I send a bad request?

推荐答案

[ApiController] 您已应用于控制器的属性添加了 自动 HTTP 400 响应到 MVC 管道,这意味着您的自定义过滤器和如果 ModelState 无效,则不会执行操作.

The [ApiController] attribute that you've applied to your controller adds Automatic HTTP 400 Responses to the MVC pipeline, which means that your custom filter and action aren't executed if ModelState is invalid.

我看到了一些影响其工作方式的选项:

I see a few options for affecting how this works:

  1. 移除[ApiController]属性

  1. Remove the [ApiController] attribute

虽然您可以只删除[ApiController] 属性,但这也会导致其提供的一些其他功能丢失,例如 绑定源参数推断.

Although you can just remove the [ApiController] attribute, this would also cause the loss of some of the other features it provides, such as Binding source parameter inference.

禁用自动 HTTP 400 响应

Disable only the Automatic HTTP 400 Responses

以下是 docs 显示了如何仅禁用此功能:

Here's an example from the docs that shows how to disable just this feature:

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

此代码位于您的 StartupConfigureServices 方法中.

This code goes inside of your Startup's ConfigureServices method.

自定义生成的自动响应

如果您只想向调用者提供自定义响应,您可以自定义返回的内容.我已经在另一个答案中描述了它的工作原理,这里.

If you just want to provide a custom response to the caller, you can customise what gets returned. I've already described how this works in another answer, here.

这篇关于在 ASP.NET Core 中到达控制器之前拦截错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆