我正在尝试从TFS服务器上的报告服务实例下载一些数据 鉴于代码应该在未加入域的计算机上运行,我想我会自己设置凭据。没有运气,得到了一个HTTP 401 Unauthorized返回。好的,所以我联系了Fiddler看看发生了什么。
但是当我得到Heisenberged时 - 电话现在顺利通过了。因此认证通过Fiddler连接,但没有它就失败了。 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
}
答案 0 :(得分: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
}
答案 1 :(得分:2)
试试这个......
var credCache = new CredentialCache();
credCache.Add(new Uri("http://teamfoundationserver/reports/........""),
"Basic",
new NetworkCredential("username", "password", "DOMAIN"));
wc.Credentials = credCache;
如果不起作用,请尝试将“Basic”替换为“Negotiate”。
答案 2 :(得分:1)
使用它时会发生什么?
wc.Credentials = CredentialCache.DefaultCredentials;
此外,您确定拥有正确的用户名,密码和域吗?
另外:我想知道当.net打破他们或类似的东西时,Fiddler是否正在改变一些unicode角色。如果您的用户/密码/域名具有unicode,请尝试将其转发为"\u2638"
而不是"☺"
。
答案 3 :(得分: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));