Peacemaker
Peacemaker

Reputation: 107

WebClient Giving 401 unauthorized error when credentials are passed

I am trying to access a webapi using WebClient. When I set the the property UseDefaultCredentials to true, I am able to access the api. But the headers in the request will have the system login user details which I want to avoid. So I tried creating a network credential and added the credential to the webclient. Then the webclient always gives me 401 unauthorized error. It does not hit the Api. Below is my Code sample:

 var webClient = new WebClient()
                {
                    //UseDefaultCredentials = true,
                    Credentials = new NetworkCredential("username", "password", "domain")

                };
                var response = webClient.DownloadStringTaskAsync("http://url/api/");

Upvotes: 0

Views: 1124

Answers (1)

Sumit Ricky
Sumit Ricky

Reputation: 11

Try creating network credentials by passing only username and password. In my case it worked.

Credentials = new NetworkCredential("username", "password"

Try accessing that API directly in the browser on the same machine. One with domain, without domain. You will see the difference.

Upvotes: 1

Related Questions