Created
October 18, 2023 09:24
-
-
Save MichalGrzegorzak/949d4ca9b80f7b6f902bf474ce313c88 to your computer and use it in GitHub Desktop.
CreateAndInitHttpClient Basic auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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