Thursday, April 17, 2008

How to add custom http header in WCF

If you want to add custom http header web service calls, there is a simple way to do it in WCF. Here is the code:

MessageHeader header
= MessageHeader.CreateHeader(
"My-CustomHeader",
"http://myurl",
"Custom Header."
);

using (Service1Client client = new Service1Client())
{
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
OperationContext.Current.OutgoingMessageHeaders.Add(header);

HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers.Add("myCustomHeader", "Custom Happy Value.");
httpRequestProperty.Headers.Add(HttpRequestHeader.UserAgent, "my user agent");
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

}
}

3 comments:

Anonymous said...

Rotem,
Thank you for the example to add HTTP header in WCF client. This has been very helpful. I wonder why MS does not make it just a little easier to do such a simple task.

Unknown said...

If you have a lot of operations, you may want to use a custom message inspector to add the header to all messages.

See this:
http://msmvps.com/blogs/paulomorgado/archive/2007/04/27/wcf-building-an-http-user-agent-message-inspector.aspx

Unknown said...

JEEBUS bless you my friend.
Ebay and WCF have been driving me BONKERS for over a day.

I give you 5 thumbs up!