find a location for property in a new city

Wednesday, 16 March 2011

WCF REST: How to get a Request header

Again WCF REST is proving secretive when it comes to getting at your Request Headers.

You can get at any custom Request headers that you may be expecting via the IncomingMessageProperties off of the OperationContext in the same way as before when you were adding custom Headers to your response.

To do this you you can write something like this:
var request = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
var version = request.Headers["ApiVersion"];

Update:

Actually, there is an easier way I found. Since this is in a REST service it is possible to use WebOperationContext which seems a lot more intuitive and concise:
var version = WebOperationContext.Current.IncomingRequest.Headers["ApiVersion"];

You will then have access to any expected Request Headers as a string.

More WCF REST:

Follow britishdev on Twitter

5 comments:

  1. You rock!
    For others trying this same thing, sending information from an asp.net program is as easy as adding a .Add:
    wc.Encoding = System.Text.Encoding.UTF8;
    wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
    wc.Headers["Content-Type"] = "application/json";
    wc.Headers.Add("myCustomHeader", "Custom Value");
    dynamic a = wc.UploadString(new Uri(url), data);

    On the server side:
    string glub = System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.Headers["myCustomHeader"];

    Thank you so much!

    ReplyDelete
  2. Thank you, it was very useful to me

    ReplyDelete