2012-05-17 15 views
1

我有一個Excel加載項C#編寫的,它連接到服務器通過獲取數據的HttpWebRequest如何處理代理正確地在.NET

一個客戶端代理設置「使用自動配置腳本」檢查,它使用了一些腳本那裏。

在這種情況下,我的插件無法連接到服務器。

因此,我打開小提琴來檢查它爲什麼失敗。然後我的插件開始工作。

我籤代理設置與小提琴手開放的,你看,它更改爲「使用代理服務器爲LAN」

我想要做同樣的事情在我的代碼,使用代理從IE設置設置和在我的代碼中使用它。

你知道如何做到這一點嗎?

我現在有如下所述,不起作用。由於

private static void SetProxyIfNeeded(HttpWebRequest request, Uri uri) 
{ 
    var stopWatch = new Stopwatch(); 
    stopWatch.Start();    
    if (_proxy == null) 
    { 

     _proxyUri = WebRequest.GetSystemWebProxy().GetProxy(uri); 
     _proxy = new WebProxy(_proxyUri, true) 
         { 
          Credentials = CredentialCache.DefaultNetworkCredentials 
         }; 
     if (_proxyUri != null && !string.IsNullOrEmpty(_proxyUri.AbsoluteUri) && !_proxy.Address.Equals(uri) && !IsLocalHost(_proxy)) 
     { 
      _realProxy = true; 
     } 
     else 
     { 
      _realProxy = false; 
     } 
    } 
    //if there is no proxy, proxy will return the same uri 
    //do we need check if client.Proxy is null or not, 
    if (_realProxy) 
    { 
     request.Proxy = _proxy; 
    } 
    stopWatch.Stop(); 
    Helper.LogError("\r\n Got proxy in " + stopWatch.ElapsedMilliseconds + "ms.\r\n"); 
} 

另外,我有一個配置文件

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler" /> 
    </configSections> 
    <appSettings> 
    <add key="log4net.Config" value="log4netConfig.xml" /> 
    </appSettings> 
    <system.net> 
    <defaultProxy enabled ="true" useDefaultCredentials = "true"> 
     <proxy usesystemdefault ="True" bypassonlocal="True"/> 
    </defaultProxy> 
    </system.net> 
</configuration> 

編輯:從他們的IT人 客戶端更新,看起來像PAC被下載,但它不是用來 我不知道爲什麼沒有使用,我指定在每個請求中使用它,除了無法指定代理的cometd外,也許這是問題所在?

回答

0

如果使用的是您的AddIn一個app.config是一個選項(我知道這是棘手的與Office加載項),你可以處理所有的代理服務器配置有:

<configuration> 
    <system.net> 
     <defaultProxy> 
      <proxy 
       usesystemdefault="true" 
       bypassonlocal="true" 
      /> 
     </defaultProxy> 
    </system.net> 
</configuration> 

請參閱MSDN上<defaultProxy> Element (Network Settings)瞭解詳情。

+0

謝謝。這可能是解決方案。但是每個用戶可能有不同的代理地址,所以我們必須手動輸入代理。我正在尋找一種方法來從IE自動獲取代理。 – toosensitive

+0

我看了http://msdn.microsoft.com/en-us/magazine/cc300743.aspx,.NET框架2.0自動處理代理,但它似乎不是 – toosensitive

+0

根據[ Element(Network Settings)](http:// msdn.microsoft.com/en-us/library/sa91de1e)設置'usesystemdefault =「true」'應該使用IE代理設置。 – Filburt