Skip to content

Instantly share code, notes, and snippets.

@MichalGrzegorzak
Created October 18, 2023 09:24
Show Gist options
  • Save MichalGrzegorzak/949d4ca9b80f7b6f902bf474ce313c88 to your computer and use it in GitHub Desktop.
Save MichalGrzegorzak/949d4ca9b80f7b6f902bf474ce313c88 to your computer and use it in GitHub Desktop.
CreateAndInitHttpClient Basic auth
private HttpClient CreateAndInitHttpClient(IHttpClientFactory httpClientFactory, WorktribeClientConfig config)
{
if (httpClientFactory == null)
throw new ArgumentNullException(nameof(httpClientFactory));
if (string.IsNullOrWhiteSpace(config.BaseUrl))
throw new ArgumentNullException("config.BaseUrl");
if (string.IsNullOrWhiteSpace(config.Username))
throw new ArgumentNullException("config.Username");
if (string.IsNullOrWhiteSpace(config.Password))
throw new ArgumentNullException("config.Password");
var httpClient = httpClientFactory.CreateClient(Constants.WorktribeHttpClient);
if (httpClient == null)
throw new NullReferenceException("HttpClient");
//basic auth
var hash = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{config.Username}:{config.Password}"));
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {hash}");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
return httpClient;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment