Using Basic Authentication with HttpClient

When using Basic Authentication with HttpClient, the header values need to be Base64 encoded. The resulting code will look like this:

var authenticationString = $"<YOUR_AUTHENTICATION_STRING>";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(authenticationString));

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);

var httpResponseMessage = await httpClient.PostAsync($"");

This was a short post, but something that confused me recently and so I thought I would share it.

Leave a comment

Your email address will not be published. Required fields are marked *