Wednesday, March 25, 2015

Sending and receiving Custom Request Headers in ASP.NET Web API

If you ever have to send any custom header information to an ASP.Net Web API Service, it is not exactly easy to figure out how to accomplish this.

This MSDN Article does a pretty good job but does not clarify several important elements: http://www.asp.net/web-api/overview/advanced/http-message-handlers

So, if you simply want to send a custom Request Header using the HttpClient class, you can use code similar to the following:

IEnumerable<string> headerValues = new List<string>() {"customValue1", "customValue2"};
httpClient.DefaultRequestHeaders.Add("CustomHeader", headerValues);



Then in ASP.NET Web API, you can consume the Request Header like so:



public IEnumerable<string> Get()
{
    const string _header = "CustomHeader";
 
    IEnumerable<string> headerValues = new List<string>();
 
    if (Request.Headers.Contains(_header))
    {
        // Check if the header value is in our methods list.
        headerValues = Request.Headers.GetValues(_header);
    }
 
    return headerValues;
}

 

If these Custom Request Headers need to be consumed throughout the application, then you can take a look at consuming them in the ApiController’s constructor instead:

 


public class ValuesController : ApiController
{
    
    IEnumerable<string> _headerValues = new List<string>();
 
    public ValuesController()
    {
        const string _header = "CustomHeader";
        
    
        if (Request.Headers.Contains(_header))
        {
            // Check if the header value is in our methods list.
            _headerValues = Request.Headers.GetValues(_header);
        }
 
        public IEnumerable<string> Get()
        {
            return _headerValues;
        }    
    }
}


No comments:

Post a Comment