这里是一点经验的简短总结

之前在用SmartClient+Remoting的方式开发业务管理系统的时候,就遇到过一次HTTP代理配置的问题。当时,由于Remoting无法自动配置代理,所以采取的办法就是在登录界面上提供代理网络配置的选项,让用户手动录入代理服务器的地址,端口,用户名和密码。

在.NET 4.0中对于Web Service和WCF,就可以通过设置WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;来自动配置大部分代理服务器。这种方式其实就是使用IE中对代理服务器的配置。

对于DefaultNetworkCredentials的使用可以参考我另外一篇博客:DefaultNetworkCredentials vs DefaultCredentials

通过以上代码配置后,并不能保证一定能正确访问,所以还需要进行如下处理:

  1. 通过代码配置为默认代理后
  2. 访问一下网络是否连通
  3. 如果没有连通,尤其访问407这个验证错误的代码,
  4. 那么就需要提示用户输入代理服务器用户名和密码

我的实现代码如下:

//参考:http://www.codeguru.com/csharp/csharp/cs_network/http/article.php/c16479
_CanConnectedIKE = false;
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://www.itke.com.cn/ping.txt");
httpReq.AllowAutoRedirect = false;
HttpWebResponse httpRes;
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
    httpRes = (HttpWebResponse)httpReq.GetResponse();
    if (httpRes.StatusCode == HttpStatusCode.OK)
    {
        httpRes.Close();
        _CanConnectedIKE = true;
    }
    httpRes.Close();
}
catch (WebException ex)
{
    if (ex.Message.Contains("407"))
    {                            
        ProxyAuthDialog dialog = new ProxyAuthDialog();
        dialog.ShowDialog();
        WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(
            dialog.Username, dialog.Password);
        try
        {
            httpReq = (HttpWebRequest)WebRequest.Create("http://www.itke.com.cn/ping.txt");
            httpRes = (HttpWebResponse)httpReq.GetResponse();
            if (httpRes.StatusCode == HttpStatusCode.OK)
            {
                httpRes.Close();
                _CanConnectedIKE = true;
            }
        }
        catch (Exception ex1)
        {
            ProgramBase.Logger.WriteException(ex1);
        }
    }
}

除了通过代码来配置默认代理外,也可以在配置文件中对WCF等进行配置,如下:

<basicHttpBinding>
  <binding name="MyClientBinding" proxyAddress="http://gateway:8080" useDefaultWebProxy="false">
  </binding>
</basicHttpBinding>
or
<customBinding>
  <binding name="MyCustomClientBinding">
    <binaryMessageEncoding />
    <httpTransport proxyAddress="http://gateway:8080" useDefaultWebProxy="false" />
  </binding>
</customBinding>
or
<system.net>
  <defaultProxy useDefaultCredentials="true">
    <proxy bypassonlocal="False" proxyaddress="http://gateway:8080" />
  </defaultProxy>
</system.net>

相关文章:

  • 2021-05-28
  • 2021-05-06
  • 2021-07-19
  • 2021-05-20
  • 2021-09-29
  • 2021-11-20
  • 2021-06-04
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
  • 2021-08-08
相关资源
相似解决方案