Click here to Skip to main content
15,887,283 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
I am trying to consume the webapi file which is on server with the console application on my machine, We have windows authentication on.
I would really appreciate if someone could help as I am trying since yesterday and searching for the answer and tried different methods too.

C#
client.BaseAddress = new Uri(baseurl);
           client.DefaultRequestHeaders.Accept.Clear();
           client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
           int anId = 100;
           HttpResponseMessage response;
           string serviceUrl = "api/contacts";

           //var Id = "{'Id':'0001'}";

           var anContact = new Contact()
           {
               Id=600,
               ContactName = "Nick",
               ContactPhNo = "789-665-345"
           };

           

           // 2. Get all employees.

           Console.WriteLine("2. Get All Employee by sending GET {0}/{1} \r\n", baseurl, serviceUrl);

           response = client.GetAsync(serviceUrl).Result;        
Posted
Updated 23-Dec-15 6:20am
v3
Comments
ZurdoDev 23-Dec-15 12:41pm    
Based on the error, it would seem you know what the problem is, doesn't it? You need to authenticate or change the page your trying to post to to allow anonymous.
swapsun 23-Dec-15 14:04pm    
I tried doing that too.

1 solution

Hi,

In order to access a WebAPI using windows authentication, you have to create a HttpClientHandler and set the credentials in it. Then, this HttpClientHandler object has to be passed to the HttpClient.

Please refer my technical tip on this for detailed explanation.

Authenticate WebAPIs with Basic and Windows Authentication[^]

Hope this helps. Happy learning!!
 
Share this answer
 
Comments
swapsun 23-Dec-15 13:34pm    
I think that helped, Thanks a lot, but now I am stuck on 404 error.

HttpClientHandler authtHandler = new HttpClientHandler()
{
Credentials = CredentialCache.DefaultNetworkCredentials
};
using (HttpClient confClient = new HttpClient(authtHandler))
{

confClient.BaseAddress = new Uri(baseurl);
confClient.DefaultRequestHeaders.Accept.Clear();
confClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

response = confClient.GetAsync(serviceUrl).Result;

if (response.IsSuccessStatusCode)
{
Mathi Mani 23-Dec-15 14:27pm    
Please check whether the URI you are using is valid, by directly putting it in the address bar of the browser.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900