System.Net.WebClient奇怪地失败了

我试图从我们的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 } 

看看这个链接:
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 } 

试试这个 …

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

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

使用它时会发生什么?

 wc.Credentials = CredentialCache.DefaultCredentials; 

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

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

我能够通过使用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));