0

我想用 API_Key 授权调用第三方 API。请找到我的代码,它返回“StatusCode:401,ReasonPhrase:'未授权',版本:1.1”
我尝试通过 2 方法添加 API 密钥,并且都给出了上述响应。请指教。

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;
}
4

0 回答 0