Paul Farry
Paul Farry

Reputation: 4768

How to Read HTTP header value

I have a WebService that is being called from an Iphone app (that I am also building)

In my webservice is it being self hosted inside a Service and it is all working well, except I would like to move a security token into the Headers of the Request so that the class objects remain neat. (If I can't get it in the header, i'll resort to putting it in the class but that's a bit ugly imo).

I have looked at the code in this http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontext.incomingmessageheaders.aspx#Y342 and I can't seem to enumerate the header value.

Looking in Fiddler, I can see the header is being passed through

POST http://192.168.1.221:11001/StockControl/json/SubmitResults HTTP/1.1
Device-Token: bwI2YiAHR4q3Ba5JVj99Cw==
Content-Type: application/json
Content-Length: 1663
User-Agent: StockManage/1.0 CFNetwork/609 Darwin/12.1.0

I'm not sure if I haven't set up my SelfHosted configuration correctly or if I haven't implemented a necessary interface .

WCF IClientMessageInspector and the incoming SOAP headers but this is using SOAP and I'm using JSON.

My Endpoint is setup using the following

WebHttpBinding jsonBind = new WebHttpBinding();
ServiceEndpoint jsonServer = host.AddServiceEndpoint(typeof(POSServer.StockControl.IStockService), jsonBind, "json");

jsonServer.Behaviors.Add(new WebHttpBehavior
{
    DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare,
    HelpEnabled = true,
    DefaultOutgoingResponseFormat = WebMessageFormat.Json
});

Finally in my SubmitResults function in my Service implementation

public bool SubmitResults(Business.StockResultData theData)
{
    DateTime uploadTime = DateTime.Now;
    int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("Device-Token", "");
    this.WriteHeaders(OperationContext.Current.IncomingMessageHeaders);
    this.WriteHeaders(OperationContext.Current.RequestContext.RequestMessage.Headers);

but index is always -1 (not found) and the WriteHeaders cannot see the header.

Upvotes: 2

Views: 3075

Answers (2)

Taran
Taran

Reputation: 3231

This works for me...where apiKey is Header name

>  var headers =OperationContext.Current.IncomingMessageProperties["httpRequest"];
            var apiToken = ((HttpRequestMessageProperty)headers).Headers["apiKey"];

Upvotes: 0

Paul Farry
Paul Farry

Reputation: 4768

After a lot of searching I believe I found the answer here . (http://social.msdn.microsoft.com/Forums/pl-PL/wcf/thread/72ee44cc-58bb-45b2-aff7-49d9bbc8176e)

HttpRequestMessageProperty reqMsg = 
          OperationContext.Current.IncomingMessageProperties["httpRequest"] as 
          HttpRequestMessageProperty;

Upvotes: 3

Related Questions