Add custom header to all responses in Web API
asp.net, asp.net-web-api, c#
Solution
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.
Problem
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()); ```