12

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

但那是当我得到海森堡的时候——电话现在顺利通过了。因此,身份验证在 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
    }
4

4 回答 4

4

看看这个链接:
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
    }
于 2009-11-29T10:42:22.223 回答
2

试试这个 ...

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

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

于 2009-06-16T16:15:49.780 回答
1

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

wc.Credentials = CredentialCache.DefaultCredentials;

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

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

于 2009-06-16T16:07:58.597 回答
1

我能够通过使用 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));
于 2011-12-08T19:19:50.100 回答