這裡是一點經驗的簡短總結
之前在用SmartClient+Remoting的方式開發業務管理系統的時候,就遇到過一次HTTP代理配置的問題。當時,由於Remoting無法自動設定代理,所以採取的辦法就是在登入介面上提供代理網路設定的選項,讓使用者手動錄入Proxy 伺服器的地址,連接埠,使用者名稱和密碼。
在.NET 4.0中對於Web Service和WCF,就可以通過設定WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;來自動設定大部分Proxy 伺服器。這種方式其實就是使用IE中對Proxy 伺服器的配置。
對於DefaultNetworkCredentials的使用可以參考我另外一篇部落格:DefaultNetworkCredentials vs DefaultCredentials
通過以上代碼配置後,並不能保證一定能正確訪問,所以還需要進行如下處理:
- 通過代碼配置為預設代理後
- 訪問一下網路是否連通
- 如果沒有連通,尤其訪問407這個驗證錯誤的代碼,
- 那麼就需要提示使用者輸入Proxy 伺服器使用者名稱和密碼
我的實現代碼如下:
custom code for set proxy//參考: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>