Add custom header to all responses in Web API

Related searches

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());

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.

Add custom header to every web api call from common place, Is this possible? Please guide. using (var client = new HttpClient()). {. var response= client .GetAsync("Myserviceurl") .Result´┐Ż 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.

Julian's answer led me to have to create the filter but only using the the System.Web (v4) and System.Web.Http (v5) namespace (MVC packages were not part of this particular project this was used on.)

using System.Web;
using System.Web.Http.Filters;
...
public class AddCustomHeaderActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);
        actionExecutedContext.ActionContext.Response.Headers.Add("name", "value");
    }
}

And add it to the global.asax to have it used on every controller/action

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

Embellish Your Web API Responses with Header Data -- Visual , When prompted for the type of scaffolding to add, select Web API 2 Controller header or any other custom headers in your HTTP responses. This way all client will receive the API responses with the added custom headers. Both above discussed middleware approaches are most preferable. However, you can also use Filters in ASP.NET Core. Add Reponse Header in Controller. Adding custom headers through the controller is easier. Please use a Reponse object to add the required custom headers.

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.

Web API versioning using a custom header, To implement versioning using a custom version header, all we have are Duration: 6:54 Posted: Mar 1, 2017 HttpControllerDispatcher sends the request to a Web API controller. You can add custom handlers to the pipeline. Message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might: Read or modify request headers. Add a response header to responses.

Neither of the above two solutions worked for me. They wouldn't even compile. Here's what I did. Added:

filters.Add(new AddCustomHeaderFilter());

to RegisterGlobalFilters(GlobalFilterCollection filters) method in FiltersConfig.cs and then added

public class AddCustomHeaderFilter : ActionFilterAttribute
{
   public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
   {
       actionExecutedContext.HttpContext.Response.Headers.Add("ServerTime", DateTime.Now.ToString());
   }
}

HTTP Response Headers in ASP.NET Core, NET Core has the flexibility to add HTTP response headers anywhere in the middleware pipeline. As you can see, in the entire lifecycle a request flows through any The actual list depends on the web server and the application. a callback that will add a custom header at the last useful minute. FYI there is an official HTTP Header that you can use to represent the DateTime a resource was last updated. It is the 'Last-Modified' Header (See section 14.29 on Section 14 page of the specification). You add it to your response like this: Response.Content.Headers.LastModified = yourResource.LastUpdatedDateTime;

According to my requirement, below single line of code serves the purpose.

System.Web.HttpContext.Current.Response.Headers.Add("Key", "Value")

I need to create a POST method in WebApi so I can send data from application to WebApi method. I'm not able to get header value. Here I have added header values in the application: using (var cl

To implement the Web API Versioning using custom header, all we need to do is to change the logic of the CustomControllerSelector class to read the version number from the custom header instead of the query string parameter. Modify the CustomControllerSelector class as shown below. The code is self-explained, so please go through the comments.

Add a response header to the HTTP response. Validate the requests before they reach the controller (i.e. Authentication and Authorization). The following diagram shows two custom handlers (Message Handler1 and Message Handler2) inserted into the Web API pipeline at the Server side.

Comments
  • This answer is mostly correct. Sometimes the content of a response could be null however. You should do actionExecutedContext.Response.Headers.Add instead.
  • Action filters could work but be careful that message handlers could prevent you even getting that far. Thus you could land up with some responses missing the header.
  • Also, bare in mind that Authorization filters run before Action filters and if your authorization filter would deny access, the custom action filter would never get to fire at all.
  • The problem with these answers is that they only apply a header to the html page, not the CSS pages, images, javascript, etc. Is this really a problem? If you run a penetration test with ZAP, it complains about the missing headers. How do you add a header to all files in an MVC app?
  • OnActionExecuted only fires if the action was executed. So if another filter prevented it from executing, then your filter won't run. This is common if you have an Authorization Filter in place and the context is not authenticated and you rely on your action filter to run on UnAuthenticated requests. To get around this, you should implement OnActionExecuting, and implement both the async and sync versions of it.
  • i think this was WebAPI 1, not sure if 2 (if that's what you are using) has slightly different bindings
  • Yes most likely that is the explanation. I am using WebAPI 2.0. But I think my version will be useful for people now looking how to add a custom header.
  • I don't think this works when an exception is thrown. How do you add headers to ALL responses?
  • IEnumerable<string> vals; response.Headers.TryGetValues("Key", out vals); string value = vals?.FirstOrDefault();