[英]Adding a response header in an ExceptionFilterAttribute in ASP .Net Core
I'm trying to add a header to responses from a.Net core Web API when an exception occurs.当发生异常时,我正在尝试向来自 .Net 核心 Web API 的响应添加标头。
I'm using an ExceptionFilterAttribute
...我正在使用ExceptionFilterAttribute
...
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
context.HttpContext.Response.Headers.Add("CorrelationId", "12345");
base.OnException(context);
}
}
For some reason the header is not sent to the client.由于某种原因,标头未发送到客户端。 I'm guessing this is something to do with responses already being formed at this point so they can't be changed?我猜这与此时已经形成的响应有关,因此无法更改它们?
I've got a custom middleware that adds a correlation id to the request context and then outputs it into the response headers.我有一个自定义中间件,它向请求上下文添加一个关联 ID,然后将其输出到响应标头中。 This doesn't fire when an exception occurs though so I need another way of doing it hence trying to use the filter.这不会在发生异常时触发,所以我需要另一种方法来尝试使用过滤器。
What should I change to get this to work?我应该改变什么才能让它工作?
Try this,试试这个,
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var correlationId = "12345";
// DO OTHER STUFF
context.HttpContext.Response.OnStarting(() =>
{
context.HttpContext.Response.Headers.Add("CorrelationId", correlationId);
return Task.CompletedTask;
});
}
}
Explicitly set context.Result
to write output from an exception filter:显式设置context.Result
以写入异常过滤器的输出:
public override void OnException(ExceptionContext context)
{
context.HttpContext.Response.Headers.Add("CorrelationId", new string[] { "12345" });
context.Result = new ObjectResult(null) { StatusCode = 500 };
context.ExceptionHandled = true;
base.OnException(context);
}
This will add the header to the actual response.这会将标头添加到实际响应中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.