Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.73/5 (3 votes)
See more:
Hi,

I want to call web api with basic authentication not authorization. plesae help me.
i tried with below code but am getting null response.

What I have tried:

C#
HttpClient client = new HttpClient();

                string authInfo = "raj" + ":" + "34sddff";
                authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);

                client.BaseAddress = new Uri("http://sample");

                HttpResponseMessage response = client.GetAsync(url).ContinueWith(task => task.Result).Result;
                    // Parse the response body. Blocking!
                    if (response.IsSuccessStatusCode)
                    {
                        var httpResponseResult = response.Content.ReadAsStringAsync().ContinueWith(task => task.Result).Result;
                        var data = JObject.Parse(httpResponseResult);
                        var responseCode= data.SelectToken("code").Value();
                        var message = data.SelectToken("message").Value();
                    }
Posted
Updated 16-Dec-19 2:20am
v2

 
Share this answer
 
 
Share this answer
 
v2
Comments
Richard Deeming 18-Sep-18 15:26pm    
That's exactly the same link as solution 1.
I think you are missing the "await" in front of client.GetAsync(url)...
 
Share this answer
 
Comments
Richard Deeming 8-Oct-19 14:28pm    
You think incorrectly - the .Result on the end forces the code to wait for the task to complete.

It's not great, and can lead to deadlocks. But it's not the cause of the problem.

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