System.Net.WebClient fails weirdly

旧街凉风 提交于 2019-12-21 07:29:07

问题


I am trying to download some data from the reporting services instance on our TFS server.
Given that the code should run on a computer that is not domain-joined, I figured that I would set the credentials myself. No luck, got a HTTP 401 Unauthorized back. Ok, so I hooked up Fiddler to see what was happening.

But that's when I got Heisenberged - the call now went through without a hitch. So the authentication goes through with Fiddler connected, but fails without it. Is the Webclient broken or am I missing something profound here?

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
    }

回答1:


Take a look at this link:
HTTP Authorization and .NET WebRequest, WebClient Classes

I had the same problem as you. I have only added one line and it started to work. Try this

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:


Try this ...

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

If that does not work, try replacing "Basic" with "Negotiate".




回答3:


What happens when you use this?

wc.Credentials = CredentialCache.DefaultCredentials;

Also, are you sure you have the correct username, password and domain?

Also: I wonder if Fiddler is changing around some unicode characters when .net breaks them or something like that. If your user/pass/domain has unicode, try escaping it out like "\u2638" instead of "☺".




回答4:


I was able to get around this error by using a CredentialCache object, as follows:

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


来源:https://stackoverflow.com/questions/791658/system-net-webclient-fails-weirdly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!