我有一个C# .NET程序(4.7.1(,如果可用,我想使用默认的系统代理。
当我将以下代码放入我的 App.Config 文件中时:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
</defaultProxy>
</system.net>
... rest of the file
</configuration>
应用程序在内核数据库中启动时崩溃.dll没有错误并立即退出。
我已经使用提琴手在本地主机上设置了一个代理(进行一些测试(
我可以在事件日志中找到以下错误,这不是很有用:
Faulting application name: myprogram.exe, version: 0.01.6652.23883, time stamp: 0x5aaf246f
Faulting module name: KERNELBASE.dll, version: 10.0.16299.15, time stamp: 0x2cd1ce3d
Exception code: 0xe0434352
Fault offset: 0x001008b2
Faulting process id: 0x1220
Faulting application start time: 0x01d3bf2e95ca9d05
Faulting application path: C:sourcemyprogram.exe
Faulting module path: C:WindowsSystem32KERNELBASE.dll
Report Id: 5a60273b-637f-4dac-ae09-5539fb563884
Faulting package full name:
Faulting package-relative application ID:
有什么想法我出错了,以及如何让默认代理在 C# .NET 程序中工作?
根据文档:
proxy
元素定义应用程序的代理服务器。如果配置文件中缺少此元素,则 .NET Framework 将使用 Internet Explorer 中的proxy
设置。
我冒昧地猜测您尝试运行此操作的计算机没有导致崩溃的Internet Explorer。
在任何情况下,添加代理服务器设置以确保您的应用程序将在未安装 Internet Explorer 的计算机上运行是有意义的。
<configuration>
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy
usesystemdefault="true"
proxyaddress="http://192.168.1.10:3128"
bypassonlocal="true"
/>
</defaultProxy>
</system.net>
</configuration>
如果要检测代理,则无法使用app.config
执行此操作,因为 .NET 中不存在该功能。相反,您必须执行以下操作:
WebProxy proxy = (WebProxy) WebRequest.DefaultWebProxy;
if (proxy.Address.AbsoluteUri != string.Empty)
{
Console.WriteLine("Proxy URL: " + proxy.Address.AbsoluteUri);
wc.Proxy = proxy;
}
参考:C# 自动检测代理设置
这就是我最终所做的(基本上是NightOwl888建议的(添加了GetSystemWebProxy
var proxy = WebRequest.GetSystemWebProxy();
_webRequestHandler = new WebRequestHandler { ClientCertificateOptions = ClientCertificateOption.Automatic };
_webRequestHandler.Proxy = proxy;
_client = new HttpClient(_webRequestHandler);
_client.BaseAddress = new Uri(connectionUrl);
_client.Timeout = new TimeSpan(0,0,0,timeoutSeconds);