How to use Basic Auth with HttpClient?

winanjaya 81 Reputation points
2023-03-07T14:53:59.6366667+00:00

Hi All,

How to use Basic Auth with HttpClient?

I use snippet codes below, but keeps getting 401, what I have missed?

                var authenticationString = $"{userName}:{userPassword}";
                var base64String = Convert.ToBase64String(
                   System.Text.Encoding.ASCII.GetBytes(authenticationString));

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);

                await _httpClient.GetAsync(url);
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,625 questions
{count} votes