Click here to Skip to main content
15,905,607 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to connect with API and get the response in JSON format. I need to put the username and password to connect to API.
While I am hitting the url in browser and putting the username and password, I am able to get the response. But while I am connecting via C# code, I am getting the below error.

StatusCode - 401
IsSuccessStatusCode - False
ReasonPhrase - Unauthorized

What I have tried:

I tried below but couldn't get through.

var acadiaUrl = "";

            HttpClientHandler handler = new HttpClientHandler();
            HttpClient httpClient = new HttpClient(handler);
            var byteArray = Encoding.ASCII.GetBytes("username:password");
            httpClient.DefaultRequestHeaders.Authorization = 
                 new AuthenticationHeaderValue
                 ("Basic", Convert.ToBase64String(byteArray));

            HttpResponseMessage response = 
                await httpClient.GetAsync(acadiaUrl);
            HttpContent content = response.Content;
Updated 2-Oct-23 2:47am
PIEBALDconsult 29-Sep-23 19:41pm    
Is it RESTful? Does it use basic authentication?

1 solution

You will have to go back to the site you got the API from and look / ask there: there is no "single rule" to handle logins that all API's must use.
Share this answer
Member 9346617 9-Oct-23 1:53am    
When I am hitting the api from chrome with required user name and password, I am getting correct response.
However, when I am doing the same from Edge (another browser), it says - "{
"status_code": 401,
"message": "Invalid credentials provided to perform this operation"
I am getting the same error while hitting from C# code. I have ensured that user name and password that I am entering for Edge and C# code are accurate.

Please help what else I need to check.

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