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

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

一个客户端的代理设置“使用自动configuration脚本”选中,它使用了一些脚本。

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

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

我检查代理设置与提琴手打开,看,它被改为“使用代理服务器为您的局域网”

我想在我的代码中做同样的事情,使用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"); } 

另外,我有一个configuration文件

 <?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无法指定代理,也许这就是问题?

如果为你的AddIn使用app.config是一个选项(我知道这对于Office Addins来说是非常棘手的),你可以在那里处理所有的代理configuration:

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

有关详细信息,请参阅MSDN上的<defaultProxy>元素(networking设置) 。