Sunday, June 1, 2014

How to pass custom headers in WCF REST service?

Often do we want to pass some data to some or maybe all our service operations. This data is usually context data such as user tokens, or environmental preferences of the user or machine. In these kind of situations, we would rather not add additional context parameters to the contracts or our services, because we don’t want to involve implementation data / context data with the business parameters of our services.
A nice and easy way to pass that data is to use Headers. In order to do this we follow these steps:

In your WCF REST service project add a Global.asax file and insert following code snippet in Application_BeginRequest method:


protected void Application_BeginRequest(object sender, EventArgs e)
   {
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
      if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
         {
             HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
             HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
             HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, accessToken");
             HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
             HttpContext.Current.Response.End();
            } 

     }

In the above code accessToken is the message which REST service can accept from any web Request.

To retrieve this header in this service use the following code:

IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
                WebHeaderCollection headers = request.Headers;
                string accessToken = headers.Get("accessToken");

Thanks