从默认Web代理获取URI

时间:2010-11-23 09:11:15

标签: c# wcf .net-3.5 proxy

我正在编写一个程序,该程序应该可以在没有代理的情况下运行,并且代理可以自动执行!它应该调用WCF服务。在此示例中,实例名为client。我还使用自编写的类(proxyHelper)来请求凭证。

 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,则它可以正常工作。那么......我怎样才能收集默认Web代理的地址?

1 个答案:

答案 0 :(得分:15)

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

以下是MSDN中描述的摘录:

  

GetProxy方法返回URI   WebRequest实例使用的   访问Internet资源。

     

GetProxy将目的地与   BypassList的内容,使用   IsBypassed方法。如果IsBypassed   返回true,GetProxy返回   目的地和WebRequest   实例不使用代理   服务器

     

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

您可以使用以下代码获取代理详细信息。请注意,传递给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/