Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

Adding a custom Http header to WCF request (C#)

I was looking for a snippet to add a custom header to WCF service request. Why? For example, to add authentication header to add Basic Authentication support. (Yes – WCF supports Basic Authorization by itself but didn’t find how to use it without SSL).

Here is the shortest way.

Use this snippet on your client side:

 using  (MyServ.ServiceClient  proxy = new  MyServ.ServiceClient ())
 {
     using  (new  System.ServiceModel.OperationContextScope (proxy.InnerChannel))
     {
         MessageHeader  head = MessageHeader .CreateHeader("Authorization" , "http://mynamespace.com/v1" , data);
         OperationContext .Current.OutgoingMessageHeaders.Add(head);
     }
 }
 

And just in case, here is how to retrieve this information from Http header on the server side:

 string  auth = OperationContext .Current.
     IncomingMessageHeaders.
     GetHeader<string >("Authorization" , "http://mynamespace.com/v1" );
 

More about OperationContextScope Class here.

Technorati Tags: ,