Get the URI from the default web proxy

2019-04-23 01:40发布

问题:

I'm writing a program that should work without proxy and with proxy with authentication - automatically! It should call a WCF service. In this example the instance is called client. I also use a self written class (proxyHelper) that requests the credentials.

 BasicHttpBinding connection = client.Endpoint.Binding as BasicHttpBinding;<br/>
 connection.ProxyAddress = _???_<br/>
 connection.UseDefaultWebProxy = false;<br/>
 connection.BypassProxyOnLocal = false;<br/>
 connection.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;<br/>
 client.ClientCredentials.UserName.UserName = proxyHelper.Username;
 client.ClientCredentials.UserName.Password = proxyHelper.Password;

I'm facing a problem getting the ProxyAddress. If I use HttpWebRequest.GetSystemWebProxy() to get actual defined proxy I see in debug mode the correct proxy address but it's a non public property. Setting UseDefaultWebProxy to true doesn't work and if I add the proxy address hard-coded and set the UseDefaultWebProxy to false it works fine. So... how can I gather the address of the default web proxy?

回答1:

The proxy has a method called GetProxy which can be used to get the Uri of the proxy.

Here's a snippet of the description from MSDN:

The GetProxy method returns the URI that the WebRequest instance uses to access the Internet resource.

GetProxy compares destination with the contents of BypassList, using the IsBypassed method. If IsBypassed returns true, GetProxy returns destination and the WebRequest instance does not use the proxy server.

If destination is not in BypassList, the WebRequest instance uses the proxy server and the Address property is returned.

You can use the following code to get the proxy details. Note that the Uri that you pass to the GetProxy method is important, as it will only return you the proxy credentials if the proxy isn't bypassed for the specified Uri.

var proxy = System.Net.HttpWebRequest.GetSystemWebProxy();

//gets the proxy uri, will only work if the request needs to go via the proxy 
//(i.e. the requested url isn't in the bypass list, etc)
Uri proxyUri = proxy.GetProxy(new Uri("http://www.google.com"));

proxyUri.Host.Dump();        // 10.1.100.112
proxyUri.AbsoluteUri.Dump(); // http://10.1.100.112:8080/