System.Net.WebClient失败奇怪

问题描述:

我想从我们的TFS服务器上的报告服务实例下载一些数据。
鉴于代码应该在未加入域的计算机上运行,​​我想我会自己设置凭据。没有运气,得到了HTTP 401 Unauthorized back。好吧,我迷上了小提琴手,看看发生了什么。System.Net.WebClient失败奇怪

但是那时我得到了Heisenberged - 现在的通话顺利进行。所以认证通过连接提琴手,但没有它失败。 Web客户端是坏的还是我在这里遗漏了深刻的东西?

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 
    } 
+11

+1使用海森堡uncertaintly原则作为动词,从来没有听说过的人之前! – 2009-04-26 23:06:02

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

添加标题行对我来说效果不错! – viperguynaz 2012-12-03 22:40:22

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

wc.Credentials = CredentialCache.DefaultCredentials; 

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

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

+3

在刚刚处理与同事相似的问题时,我们确定提琴手正在使用您的本地凭证访问Web服务,因为Asp.Net应用程序中的代码将使用asp.net用户的凭据,没有权限。 – travis 2009-07-02 15:51:11

尝试......

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

如果还是不行,请尝试使用“谈判”取代“基本”。

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