从默认Web代理获取URI

Jan*_*Jan 8 c# wcf proxy .net-3.5

我正在编写一个程序,应该可以在没有代理的情况下使用代理并使用身份验证 - 自动!它应该调用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;
Run Code Online (Sandbox Code Playgroud)

我遇到了获取ProxyAddress的问题.如果我HttpWebRequest.GetSystemWebProxy()用来获取实际定义的代理,我在调试模式下看到正确的代理地址,但它是非公共属性.将UseDefaultWebProxy设置为true不起作用,如果我添加硬编码的代理地址并将UseDefaultWebProxy设置为false,则它可以正常工作.那么......我怎样才能收集默认Web代理的地址?

Rei*_*ica 15

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

以下是MSDN中描述的片段:

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

GetProxy使用IsBypassed方法将目标与BypassList的内容进行比较.如果IsBypassed返回true,则GetProxy返回目标,而WebRequest实例不使用代理服务器.

如果destination不在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"));

Console.WriteLine(proxyUri.Host);
Console.WriteLine(proxyUri.AbsoluteUri);
Run Code Online (Sandbox Code Playgroud)

  • 工作完美,非常感谢!我刚刚添加了一行:Uri proxyAddress = proxy.GetProxy(client.Endpoint.Address.Uri); (3认同)