C# – How to get WebClient (webservice client) to automatically use the default proxy server

cPROXYsoapweb serviceswebclient

I'm calling a webservice from a WinForms app. Everything works fine when a proxy server isn't in use, however when a proxy is being used, the app crashes as instead of the XML response it's expecting for the SOAP request, it gets an HTML error page saying "Authentication Required".

It seems you can set the proxy manually like this:

WebClient client = new WebClient();
WebProxy wp = new WebProxy("proxy server url here");
client.Proxy = wp;

…but to some extent, it seems to be seeing the proxy server anyway WITHOUT doing the above, as the error generated is actually coming from the proxy server. It just doesn't seem to be picking up the Windows Authentication login credentials from the user's computer. How can I force it to do this?

On my own machine if I simulate this using Fiddler (and enabling the "Require Proxy Authentication" option), I get a dialog pop up asking for the login credentials, but this doesn't seem to happen on my client's machines (who use a real hardware proxy – McAfee Web Gateway).

How can I handle this? Do I need to provide a dialog for users to configure the server manually or is there a setting to tell WebClient to use the Windows default proxy and the user's own login credentials?

Update

Seems like you can pick up the proxy server using the code below, but that doesn't cause the authentication dialog to appear in all situations (works on some PCs but not on others):

IWebProxy defaultProxy = WebRequest.DefaultWebProxy;
if (defaultProxy != null)
{
    defaultProxy.Credentials = CredentialCache.DefaultCredentials;
    client.Proxy = defaultProxy;
}

If the code above is correct, I don't understand why some users would not be prompted for their credentials. Do I have to put in my own code to collect the user credentials and supply them to the WebRequest object?

Best Answer

Try adding

  <system.net>
    <defaultProxy useDefaultCredentials="true" />
  </system.net>

to your app.config file