Add custom header to all responses in Web API

后端 未结 8 980
我寻月下人不归
我寻月下人不归 2020-12-07 18:30

Simple question, and I am sure it has a simple answer but I can\'t find it.

I am using WebAPI and I would like to send back a custom header to all responses (server

相关标签:
8条回答
  • 2020-12-07 19:21

    I had the same problem while trying to add a new header to the whole controller, just add "services.AddHttpContextAccessor();" to startup.cs then create your controller

    public class EnController : Controller{
    
            public EnController(IHttpContextAccessor myHttpAccessor)
            {
    
                myHttpAccessor.HttpContext.Response.Headers.Add("Content-Language", "en-US");
    
            }
    
           ... more methods here... 
    
    }

    0 讨论(0)
  • 2020-12-07 19:22

    Previous answers to this question don't address what to do if your controller action throws an exception. There are two basic ways to get that to work:

    Add an exception filter:

    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Filters;
    
    public class HeaderAdderExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Response == null)
                context.Response = context.Request.CreateErrorResponse(
                    HttpStatusCode.InternalServerError, context.Exception);
    
            context.Response.Content.Headers.Add("header", "value");
        }
    }
    

    and in your WebApi setup:

    configuration.Filters.Add(new HeaderAdderExceptionFilter());
    

    This approach works because WebApi's default exception handler will send the HttpResponseMessage created in a filter instead of building its own.

    Replace the default exception handler:

    using System.Net;
    using System.Net.Http;
    using System.Web.Http.ExceptionHandling;
    using System.Web.Http.Results;
    
    public class HeaderAdderExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            HttpResponseMessage response = context.Request.CreateErrorResponse(
                HttpStatusCode.InternalServerError, context.Exception);
            response.Headers.Add("header", "value");
    
            context.Result = new ResponseMessageResult(response);
        }
    }
    

    and in your WebApi setup:

    configuration.Services.Replace(typeof(IExceptionHandler), new HeaderAdderExceptionHandler());
    

    You can't use both of these together. Okay, well, you can, but the handler will never do anything because the filter already converted the exception into a response.

    Super important to note that as written, this code will send all the exception details to the client. You probably don't want to do this in production, so check out all the available overloads on CreateErrorResponse() and pick which one suits your needs.

    0 讨论(0)
提交回复
热议问题