4

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

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for taking your time, Actually I am using Windows Authentication
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.