c# - .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 在成功时发生,即使发生异常也是如此。
解决方案
下图显示了这些过滤器在请求和响应生命周期中如何在过滤器管道中交互。
根据您的代码,SignResponseFilter 是一个结果过滤器,因此,从上图中我们可以知道,当异常执行时,它会先触发异常过滤器,而不是触发结果过滤器。因此,不会发生 SignResponse。
如果您想将其他过滤器与异常过滤器一起使用,您可以考虑使用操作过滤器。
更多详细信息,请查看ASP.NET Core 中的过滤器
推荐阅读
- python - 关于在 Python 中创建自己的 complex() 函数的建议?
- azure - 获取逻辑应用工作流运行时执行的操作数
- network-programming - 如何通过 SNMP 在 Linux/Redhat 中获取平均磁盘响应时间
- javascript - 在 HTML 中传递 url 中的变量
- android - Android Context的扩展功能在哪里?
- wordpress - 如何获取元名称
- c# - 线程安全的任务队列等待
- python - QCalendarWidget 使用 pyqt5 点击年份
- spring - Spring Batch:在内存数据库中用于 Spring Batch 元数据表
- javascript - 如何在没有 xhr、fetch 甚至 websockets 的情况下发送 api 请求?