Is it possible to set headers on a WebChannelFactory
? If I were using a WebClient
object, I could do something like this:
WebClient client = new WebClient();
client.Headers.Add("referer", "http://stackoverflow.com");
client.Headers.Add("user-agent", "Mozilla/5.0");
But I haven't been able to figure out a way to modify the headers on a WebChannelFactory
.
The
WebChannelFactory
class itself doesn't take any HTTP headers, but you can add them to the currentWebOperationContext
given that you create a new scope for it to work on - see below.This works, but it's fairly verbose - you essentially need to create a new scope for each call if you want to add outgoing headers to it.
Another option is to wrap the client in a client class to do the scoping and header adding for you. Using a class derived from
ClientBase<T>
is an easy way to do that. The code below is the complete sample for this question, with both options (using scope directly, using client base-derived class) for adding HTTP headers in requests from proxies created byWebChannelFactory
.