System.Net.WebClient出现奇怪的故障

12
我正在尝试从我们的TFS服务器上的报告服务实例下载一些数据。
考虑到代码应该在未加入域的计算机上运行,我决定自己设置凭据。但不幸的是,我得到了HTTP 401未经授权的错误。于是我连接了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
    }

12
使用海森堡不确定原理作为动词,加一分!我以前从未听说过这个用法。 - Robert Venables
4个回答

4

请看这个链接:
HTTP授权和.NET WebRequest、WebClient类

我跟你有一样的问题。我只加了一行代码,就可以正常工作了。你也试试这个方法吧。

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;

如果那不起作用,尝试将“Basic”替换为“Negotiate”。

1

当你使用这个时会发生什么?

wc.Credentials = CredentialCache.DefaultCredentials;

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

还有:我想知道是否 Fiddler 在 .net 破坏它们时改变了一些 Unicode 字符之类的东西。如果您的用户/密码/域名包含 Unicode,请尝试像 "\u2638" 这样转义它们,而不是使用 "☺"


3
刚刚与同事讨论一个类似的问题时,我们发现Fiddler正在使用您的本地凭据访问Web服务,而Asp.Net应用程序中的代码会使用asp.net用户的凭据,这些凭据很可能没有权限。 - travis

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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接