Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom header to all responses in Web API

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 date/time requested by a dev for syncing purposes).

I am currently struggling to find a clear example of how, in one place (via the global.asax or another central location) I can get a custom header to appear for all responses.


Answer accepted, here is my filter (pretty much the same) and the line i added to the Register function of the WebApi config.

NOTE: The DateTime stuff is NodaTime, no real reason just was interested in looking at it.

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)     {         actionExecutedContext.Response.Content.Headers.Add("ServerTime", Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()).ToString());     } 

Config Line:

config.Filters.Add(new ServerTimeHeaderFilter()); 
like image 322
Modika Avatar asked Dec 03 '13 11:12

Modika


People also ask

How do I add a header to API response?

Adding Custom Header for Individual Response We create a very basic HTTP GET endpoint. Within this endpoint, we access the Response object through the HttpContext object. Then, we add a new header, with the name of x-my-custom-header and a value of individual response .

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

Can we set response header?

And you can wonder what the difference is. But think about it for a second, then do this exercise. Draw a line from the HttpResponse method to the method's behavior.

How do I send a custom response in Web API?

Implementing a custom response handler in Web API. Create a new Web API project in Visual Studio and save it with the name of your choice. Now, select the Web API project you have created in the Solution Explorer Window and create a Solution Folder. Create a file named CustomResponseHandler.


2 Answers

For that you can use a custom ActionFilter (System.Web.Http.Filters)

public class AddCustomHeaderFilter : ActionFilterAttribute {     public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)     {        actionExecutedContext.Response.Headers.Add("customHeader", "custom value date time");     } } 

You can then apply the filter to all your controller's actions by adding this in the configuration in Global.asax for example :

GlobalConfiguration.Configuration.Filters.Add(new AddCustomHeaderFilter()); 

You can also apply the filter attribute to the action that you want without the global cofiguration line.

like image 56
Tomasz Jaskuλa Avatar answered Oct 02 '22 00:10

Tomasz Jaskuλa


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.

like image 24
Warren Rumak Avatar answered Oct 01 '22 23:10

Warren Rumak