Matin Habibi
Matin Habibi

Reputation: 720

(401) Unauthorized Error When Calling Web API from a Console Application

When I call my WEB API from my Console Application, I encounter:

The remote server returned an error: (401) Unauthorized.

This application runs in Interanet (Windows Authentication)

            Uri uri = new Uri("http://myServer/api/main/foo");
            WebClient client = new WebClient();
            client.Credentials = CredentialCache.DefaultCredentials;

            using (Stream data = client.OpenRead(uri))
            {
                using (StreamReader sr = new StreamReader(data))
                {
                    string result = sr.ReadToEnd();
                    Console.WriteLine(result);
                }
            }

Updated

If I replace

client.Credentials = CredentialCache.DefaultCredentials;

with this line

client.Credentials = new NetworkCredential( username, password);

it works fine but I need the current credential to be set automatically.

Any idea? Thanks in advance ;)

Upvotes: 4

Views: 6900

Answers (2)

Toan Nguyen
Toan Nguyen

Reputation: 11601

You use the default windows credentials here

client.Credentials = CredentialCache.DefaultCredentials;

Specify the credential that you want to authenticate using the following code:

var credential = new NetworkCredential(, , );

serverReport.ReportServerCredentials.NetworkCredentials = credential;

Upvotes: 2

Usman
Usman

Reputation: 343

following line is the cause of this behaviour :

client.Credentials = CredentialCache.DefaultCredentials;

Actually this line assigns the credentials of the logged in user or the user being impersonated ( which is only possible in web applications ) , so what I believe is that you have to provide credentials explicitly (http://msdn.microsoft.com/en-us/library/system.net.credentialcache(v=vs.110).aspx) , thanks.

Upvotes: 0

Related Questions