2010-11-23 31 views
8

我正在编写一个程序,该程序应该可以在没有代理的情况下使用代理进行身份验证 - 自动执行!它应该调用一个WCF服务。在这个例子中,该实例被称为client。我也使用一个自己写的类(proxyHelper)请求凭证。从默认的Web代理获取URI

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; 

我正在面临获取ProxyAddress的问题。如果我使用HttpWebRequest.GetSystemWebProxy()获取实际定义的代理服务器,我在调试模式下看到正确的代理地址,但它是非公有财产。将UseDefaultWebProxy设置为true不起作用,如果我添加代理地址硬编码并将UseDefaultWebProxy设置为false,它将正常工作。那么......我如何收集默认网页代理的地址?

回答

15

该代理有一个名为GetProxy的方法,可用于获取代理的Uri。

这里的描述的片段从MSDN:

的GetProxy方法返回URI 的WebRequest实例用来 访问互联网资源。

GetProxy比较目的地和 BypassList的内容,使用 IsBypassed方法。如果IsBypassed 返回true,则GetProxy返回 目标,并且WebRequest 实例不使用代理 服务器。

如果目的地不在BypassList, 的WebRequest实例使用代理服务器 和地址属性是 返回。

您可以使用以下代码来获取代理详细信息。请注意,您传递给GetProxy方法的Uri非常重要,因为如果未针对指定的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/ 
+3

完美的作品,非常感谢!我只是添加了这一行:Uri proxyAddress = proxy.GetProxy(client.Endpoint.Address.Uri); – Jan 2010-11-23 10:07:31