【发布时间】:2020-11-13 13:41:23
【问题描述】:
如何在控制器中添加一个过滤器作为装饰器,以便在启动时添加过滤器后触发?
即 我的 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 在成功时发生,即使发生异常也是如此。
【问题讨论】:
-
IAsyncAlwaysRunResultFilter可能就是您要找的。span>
标签: c# asp.net-core dependency-injection