如何在 .NET 中正确处理代理



我有一个用C#编写的Excel AddIn,它连接到服务器以通过httpwebrequest获取数据

一个客户端选中了代理设置"使用自动配置脚本",它在那里使用了一些脚本。

在这种情况下,我的插件无法连接到服务器。

所以我打开小提琴手检查它为什么失败。 然后我的插件开始工作。

我在打开小提琴手的情况下检查了代理设置,看,它已更改为"为您的 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("rn Got proxy in " + stopWatch.ElapsedMilliseconds + "ms.rn");
}

另外,我还有一个配置文件

<?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,但没有被使用我不知道为什么不使用它,我指定在每个请求中使用它,除了无法指定代理的彗星,也许这就是问题所在?

如果可以选择为您的

加载项使用 app.config(我知道这对于 Office 加载项很棘手(,您可以在那里处理所有代理配置:

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

有关详细信息,请参阅 MSDN 上的 元素(网络设置(。

最新更新