简体   繁体   中英

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.

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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM