Dan*_*iel 12 .net proxy webclient
我正在尝试弄清楚如何在使用System.Net.WebClient类时强大地处理代理身份验证错误(HTTP 407状态代码).
在该领域,我们看到许多用户接收到407代理身份验证WebException,但我不确定什么是一个好的默认策略.在.Net 2.0/3.5中,代理身份验证设置应该从Internet Explorer系统设置继承.Firefox,Opera和Chrome使用这些相同的设置.
这是我们使用的基本代码:
using System.Net;
string url = "http://www.mysite.com";
WebClient webClient = new WebClient();
byte[] data = webClient.DownloadFile(url);
Run Code Online (Sandbox Code Playgroud)
当此代码失败时,我们打开用户的浏览器并将其发送到帮助页面.从我们的网络日志中,我们知道这些客户可以在其浏览器中成功连接.也许他们在进入我们的帮助页面之前手动输入他们的代理用户名和密码?我们不知道.
似乎我们可以使用WebClient.UseDefaultCredentials,但是如果WebClient正在使用系统设置,这似乎是多余的.
任何帮助表示赞赏.
Eri*_*Law 11
如果代理身份验证使用BASIC或DIGEST,则Internet Explorer不会持久缓存/重用代理身份验证凭据.对于Negotiate/NTLM,将提供默认凭据.
因此,即使.NET继承自IE设置,除非您恰好在IE中运行,否则您将无法获得对Basic/Digest的代理身份验证的任何"免费"支持.您需要提示用户或提供配置屏幕.
Fiddler(www.fiddler2.com)在"规则"菜单上具有"请求代理身份验证"选项,您可以使用该选项模拟此方案以进行测试.
我们通过添加一个配置对话框解决了这个问题,该对话框允许用户选择"使用代理".如果完成此设置,我们使用这些参数(地址,凭证...).如果不是 - 我们假设可以在没有任何手动交互的情况下建立连接.如果出现错误,我们会这样做:a.)再次尝试使用默认凭据b.)弹出一个信息,配置中的设置可以帮助...
如果通过"默认凭据"(Windows用户)完成代理身份验证,则IE也会对身份验证错误做出反应并在此情况下发送默认凭据.如果这不起作用,则会打开凭据对话框.我不确定所有的浏览器都是这样处理的 - 但你可以简单地尝试使用fiddler,这样你就可以看到发生了什么.
小智 6
我知道这是一篇旧文章,但是我在使用WebClient在SSIS 2008R2(SQL Server Integration Services)脚本任务(VB.NET代码)中通过代理服务器下载XML文件到通过SSL保护的远程站点时遇到了类似的问题这也需要身份验证.
花了一段时间才找到解决方案,这篇文章在代理方面有所帮助.下面是适合我的脚本代码.可能对搜索类似的人有用.
Dim objWebClient As WebClient = New WebClient()
Dim objCache As New CredentialCache()
'https://www.company.net/xxxx/resources/flt
Dim strDownloadURL As String = Dts.Variables("FileURL").Value.ToString
'apiaccount@company.net
Dim strLogin As String = Dts.Variables("FileLogin").Value.ToString
'sitepassword
Dim strPass As String = Dts.Variables("FilePass").Value.ToString
'itwsproxy.mycompany.com
Dim strProxyURL As String = Dts.Variables("WebProxyURL").Value.ToString
'8080
Dim intProxyPort As Integer = Dts.Variables("WebProxyPort").Value
'Set Proxy & Credentials as a Network Domain User acc to get through the Proxy
Dim wp As WebProxy = New WebProxy(strProxyURL, intProxyPort)
wp.Credentials = New NetworkCredential("userlogin", "password", "domain")
objWebClient.Proxy = wp
'Set the Credentials for the Remote Server not the Network Proxy
objCache.Add(New Uri(strDownloadURL), "Basic", New NetworkCredential(strLogin, strPass))
objWebClient.Credentials = objCache
'Download file, use Flat File Connectionstring to save the file
objWebClient.DownloadFile(strDownloadURL, Dts.Connections("XMLFile").ConnectionString)
Run Code Online (Sandbox Code Playgroud)