【问题标题】:System.Net.WebClient fails weirdlySystem.Net.WebClient 奇怪地失败了
【发布时间】:2009-04-26 21:41:09
【问题描述】:

我正在尝试从 TFS 服务器上的报告服务实例下载一些数据。
鉴于代码应该在未加入域的计算机上运行,​​我想我会自己设置凭据。不走运,得到了 HTTP 401 Unauthorized 回复。好的,所以我连接了 Fiddler 看看发生了什么。

但那是我接到Heisenberged 的时候——电话现在顺利通过了。因此,身份验证在 Fiddler 连接的情况下通过,但没有它就失败。 Webclient 是坏了还是我在这里遗漏了一些深刻的东西?

private void ThisWorksWhenDomainJoined()
    {
        WebClient wc = new WebClient();
        wc.Credentials = CredentialCache.DefaultNetworkCredentials;
        wc.DownloadString("http://teamfoundationserver/reports/........");  //Works
    }

    private void ThisDoesntWork()
    {
        WebClient wc = new WebClient();
        wc.Credentials = new NetworkCredential("username", "password", "domain");
        wc.DownloadString("http://teamfoundationserver/reports/........");  //blows up wih HTTP 401
    }

【问题讨论】:

  • +1 将海森堡不确定原理用作动词,以前从未听说过!

标签: c# webclient system.net


【解决方案1】:

看看这个链接:
HTTP Authorization and .NET WebRequest, WebClient Classes

我和你有同样的问题。我只添加了一行,它开始工作了。试试这个

private void ThisDoesntWork()
    {
        WebClient wc = new WebClient();
        wc.Credentials = new NetworkCredential("username", "password", "domain");
        //After adding the headers it started to work !
        wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
        wc.DownloadString("http://teamfoundationserver/reports/........");  //blows up wih HTTP 401
    }

【讨论】:

    【解决方案2】:

    试试这个...

    var credCache = new CredentialCache();
    credCache.Add(new Uri("http://teamfoundationserver/reports/........""),
                          "Basic", 
                          new NetworkCredential("username", "password", "DOMAIN"));
    wc.Credentials = credCache;
    

    如果这不起作用,请尝试将“基本”替换为“协商”。

    【讨论】:

      【解决方案3】:

      当你使用它时会发生什么?

      wc.Credentials = CredentialCache.DefaultCredentials;
      

      另外,您确定您拥有正确的用户名、密码和域吗?

      另外:我想知道当 .net 破坏它们或类似的东西时,Fiddler 是否会改变一些 unicode 字符。如果您的用户/密码/域具有 unicode,请尝试将其转义为 "\u2638" 而不是 "☺"

      【讨论】:

      • 刚刚与同事解决类似问题时,我们确定 fiddler 正在使用您的本地凭据访问 Web 服务,而 Asp.Net 应用程序中的代码将使用 asp.net 用户的凭据,很可能没有权限。
      【解决方案4】:

      我可以通过使用 CredentialCache 对象来绕过这个错误,如下所示:

      WebClient wc = new WebClient();
      CredentialCache credCache = new CredentialCache();
      credCache.Add(new Uri("http://mydomain.com/"), "Basic",
      new NetworkCredential("username", "password"));
      
      wc.Credentials = credCache;
      
      wc.DownloadString(queryString));
      

      【讨论】:

        猜你喜欢
        • 2012-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-21
        • 1970-01-01
        • 2019-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多