I'm trying to add a header to responses from a .Net core Web API when an exception occurs.
I'm using an 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. 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?
Explicitly set context.Result
to write output from an exception filter:
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.