13

I have an old application that uses the classic Web Service Proxy to interact with a Java Web Service. A while back the Web Service hoster decided to require a custom HTTP header to be sent with each request in order to access the service - otherwise the requests are thrown out outright (looks like this is some sort of router requirement). Regardless of what the reason I need to inject a custom HTTP header into the request.

Is there any way to interact with the actual Http client to do things like add custom headers?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Rick Strahl
  • 17,302
  • 14
  • 89
  • 134
  • I came across this problem when our IT implemented Apache mod_security which was looking for the Accept header, and found the top-voted solution below to work. – Dean Radcliffe Jan 07 '13 at 23:11

1 Answers1

21

You should be able to do this by overriding the GetWebRequest method of the proxy class in a partial class in a separate file. After calling the base class method, you should be able to modify the returned HttpWebRequest however you like, then return it from the method:

public partial class MyServiceProxy {
    protected override WebRequest GetWebRequest(Uri uri) {
        HttpWebRequest request = (HttpWebRequest) base.GetWebRequest(uri);
        // do what you will with request.
        return request;
    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 1
    Yup that does the trick. I'm bascially generating proxies via code and I was able to generate the class and inject some code to add headers by adding a Headers property that's checked and used in GetWebRequest to add additional headers. Ugly, but it works great! – Rick Strahl Aug 21 '09 at 07:15
  • thanks for the solution. How can I use this process with my web service client project? – Mehmet Jun 02 '10 at 09:16
  • @Jack: this is the web service client project. Also, you're better off using WCF if you have the choice. – John Saunders Jun 02 '10 at 18:29
  • I m developing client project too. How can I use this override process? – Mehmet Jun 03 '10 at 05:18
  • @Jack: the code above _is_ the client project. Use the code above. – John Saunders Jun 03 '10 at 07:11
  • 2
    @Jack - you can add the above code into a new class file (or if you know you won't regenerate the service into the generated service class file). It's effectively an override to the generated proxy class. Just make sure the classname and namespace are the same as your generated proxy class. – Rick Strahl Sep 20 '11 at 22:01
  • this is a related question that might be helpfull: http://stackoverflow.com/questions/897782/how-to-add-custom-http-header-for-c-sharp-web-service-client-consuming-axis-1-4 – Alberto de Paola Jun 28 '12 at 18:48