首页 > 解决方案 > .NET Core 中的过滤器顺序

问题描述

如何在控制器中添加过滤器作为装饰器以在启动时添加过滤器后触发?

即我的 Startup.cs 看起来像这样:

services.AddControllers(options =>
            {
                options.Filters.Add<MyErrorHandlingFilter>();
            });

我的控制器:

[HttpPost()]
[SignResponseFilter]
public async Task<ActionResult> DoSomething([FromBody] request)
{
  // does stuff and causes an exception(the MyErrorHandlingFilter.OnExceptionAsync() to be called)
}

我的 SignResponseFilter:公共类 SignResponseFilter:TypeFilterAttribute {

    public SignResponseFilter() : base(typeof(SignResponseFilterImplementation))
    {
    }
    private class SignResponseFilter: IAsyncResultFilter
    {
        private readonly ISign _signer;
        public SignResponseImplementation(ISign signer)
        {
            _signer= signer;
        }

        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            await next();

            var response = await ResponseBodyReader.ReadResponseBody(context.HttpContext.Response);

            var signature = await _signer.signIt(response);

            context.HttpContext.Response.Headers.Add("myheader", signature);
        }
    }
}

MyErrorHandlingerfilter:

public class MyErrorHandlingerfilter: ExceptionFilterAttribute
    {
        private readonly IFormatter _formatter;
        public CustomErrorHandlerFilterAttribute(IFormatter fortmatter)
        {
            _formatter = fortmatter;
        }

        public override async Task OnExceptionAsync(ExceptionContext context)
        {
             _formatter.DoFormatting(); // does some formatting

            await base.OnExceptionAsync(context);
        }

我的问题是发生异常时会跳过 SignResponseFilter 。MyErrorHandlingFilter 会进行格式化。我希望 SignResponse 在成功时发生,即使发生异常也是如此。

标签: c#asp.net-coredependency-injection

解决方案


下图显示了这些过滤器在请求和响应生命周期中如何在过滤器管道中交互。

在此处输入图像描述

根据您的代码,SignResponseFilter 是一个结果过滤器,因此,从上图中我们可以知道,当异常执行时,它会先触发异常过滤器,而不是触发结果过滤器。因此,不会发生 SignResponse。

如果您想将其他过滤器与异常过滤器一起使用,您可以考虑使用操作过滤器。

更多详细信息,请查看ASP.NET Core 中的过滤器


推荐阅读