Enabling HTTP proxy for .NET webservice client

Have you ever written code that makes external (Soap) webservice calls? Tried that same code on your company network? Most of the time, this does not work very well due to a proxy server sitting in between, requiring authentication etc.

You can start tweaking your Web.config file to set this proxy the right way, or you can override the generated web service class and include the following code snippet:

[code:c#]

using System;
using System.Net;

public class SomethingProxyEnabledService : com.example.service.something {
    protected override System.Net.WebRequest GetWebRequest(Uri uri) {
        WebRequest request = base.GetWebRequest(uri);

        request.Proxy = WebRequest.DefaultWebProxy;
        request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;

        return request;
    }
}

[/code]

The only thing left to do is use this "SomethingProxyEnabledService" class instead of the regular "com.example.service.something". There you go, automagical proxy authentication!

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment

avatar

4 responses

  1. Avatar for Pablo Szittyay
    Pablo Szittyay May 15th, 2008

    I have an application that consumes from a RssFeed. All works fine in development, but when i try in the server (Windows Server 2003), with a proxy configuration i get the folliwing error.

    Service name could not be resolved

    The server has a proxy configuration. Do you know how to cnfigure the WebRequest object, so that it uses the proxy.

  2. Avatar for maartenba
    maartenba May 15th, 2008

    You can set request.Proxy to a custom Proxy instance which mimics the configuration on your server.

  3. Avatar for Pablo Szittyay
    Pablo Szittyay May 15th, 2008

    Thanks for respondig so soon. Woled it be to much trouble to give me an example of how to configure the proxy of the web request. I have tried, using the following code:

    WebRequest request = WebRequest.Create(forecastUrl);
    request.Proxy = new WebProxy ("172.16.15.235",8080);
    request.Credentials = new NetworkCredential ("degas","xxxx","172.16.15.235:8080");
    WebResponse response = request.GetResponse();

    On the proxy (wich is the way out to consume the Rssfeed) and i have set the credentials of the proxy.
    It doesn`t work, i sure that i am doing something wrong. Do you know what? if you have an example it would be great.
    Thanks a lot

  4. Avatar for Pablo Szittyay
    Pablo Szittyay May 15th, 2008

    Sorry, the code i posted before worked like a charm, it was a problem with the user "degas". Thanks a lot