代码之家  ›  专栏  ›  技术社区  ›  Daniel

System.Net.WebClient与代理身份验证407错误

  •  12
  • Daniel  · 技术社区  · 17 年前

    我试图弄清楚如何稳健地处理代理身份验证错误(HTTP) 407状态代码),当使用System.Net.WebClient类时。

    在现场,我们看到许多用户正在接收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);
    

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

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

    感谢您的帮助。

    3 回复  |  直到 17 年前
        1
  •  11
  •   EricLaw    17 年前

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

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

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

        2
  •  6
  •   ManniAT    17 年前

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

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

        3
  •  6
  •   Community Mohan Dere    12 年前

    花了一段时间找到了一个解决方案,这篇文章在代理方面起到了帮助作用。下面是为我工作的脚本代码。可能对搜索类似内容的人有用。

        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)