'API call (httpclient / IHttpClientFactory ) with API_Key Authorization
I want to call third party API with API_Key Authorization.
Please find my code and it return "StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1"
I tried to add API Key by 2 approach and both gives above response. Please advise.
var data = new StringContent(JsonConvert.SerializeObject(DocumentRequest), Encoding.UTF8, "application/json");
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
{
return true;
};
using (var client = new HttpClient(httpClientHandler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(apiKey, apiKeyValue);
client.DefaultRequestHeaders.Add(apiKey, apiKeyValue);
var response = await client
.PostAsync(apiEndPoint, data, cancellationToken)
.ConfigureAwait(false);
var errorResponse = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
_logger.LogError("Request rejected by validation process " + errorResponse);
throw new Exception($"{nameof(response.StatusCode)}:{response.StatusCode}:{errorResponse}, Request rejected.");
}
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return responseBody;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
