How can I get WebClient (webservice client) to automatically use the default proxy server?

雨燕双飞 提交于 2019-12-06 21:18:52

问题


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?


回答1:


Try adding

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

to your app.config file




回答2:


using (WebClient webClient = new WebClient())
{

    webClient.UseDefaultCredentials = true;
    webClient.Proxy = WebRequest.GetSystemWebProxy();
}

this should work




回答3:


First try to use this:

WebProxy proxy = (WebProxy) WebRequest.DefaultWebProxy;
if (proxy.Address.AbsoluteUri != string.Empty)
{
    Console.WriteLine("Proxy URL: " + proxy.Address.AbsoluteUri);
    client.Proxy = proxy;
}

if this does not work try with:

WebProxy proxy = WebProxy.GetDefaultProxy()
client.Proxy = proxy;


来源:https://stackoverflow.com/questions/16966486/how-can-i-get-webclient-webservice-client-to-automatically-use-the-default-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!