12

我试图弄清楚在使用 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);

当此代码失败时,我们打开用户的浏览器并将他们发送到帮助页面。从我们的网络日志中,我们知道这些客户可以在他们的浏览器中成功连接。也许他们在进入我们的帮助页面之前手动输入了他们的代理用户名和密码?我们不知道。

看起来我们可以使用 WebClient.UseDefaultCredentials,但是如果 WebClient 仍然使用系统设置,这似乎是多余的。

任何帮助表示赞赏。

4

3 回答 3

11

如果代理身份验证使用 BASIC 或 DIGEST,Internet Explorer 不会永久缓存/重用代理身份验证凭据。对于协商/NTLM,将提供默认凭据。

因此,即使 .NET 继承自 IE 设置,除非您碰巧在 IE 中运行,否则您不会获得对 Basic/Digest 代理身份验证的任何“免费”支持;您需要提示用户或提供配置屏幕。

Fiddler (www.fiddler2.com) 在“规则”菜单上有“请求代理身份验证”选项,您可以使用它来模拟此场景以进行测试。

于 2009-07-30T03:11:04.450 回答
6

我们通过添加允许用户选择“使用代理”的配置对话框解决了这个问题。如果完成此设置,我们将使用这些参数(地址、凭据...)。如果不是 - 我们假设可以在没有任何手动交互的情况下建立连接。如果出现错误,我们会:a.) 使用默认凭据重试 b.) 弹出配置中的设置可以帮助的信息...

如果代理身份验证是通过“默认凭据”(Windows 用户)完成的,IE 也会对身份验证错误做出反应,并在这种情况下发送默认凭据。如果这不起作用,它将打开一个凭据对话框。我不确定是否所有浏览器都以这种方式处理 - 但您可以简单地使用 fiddler 尝试一下,这样您就可以看到发生了什么。

于 2009-07-29T20:21:44.277 回答
6

我知道这是一篇旧文章,但我在尝试通过代理服务器在 SSIS 2008R2(SQL Server 集成服务)脚本任务(VB.NET 代码)中使用 WebClient 将 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)
于 2012-12-04T11:49:44.153 回答