Reputation: 350
I have to issue when I am calling external service I have the following error
The SSL connection could not be established, see inner exception.
after long search I find that I have to add servercertificatecustomvalidationcallback
to my HttpClient
My code is like this
public class ApiClient
{
private readonly HttpClient _apiClient;
public ApiClient(HttpClient apiClient)
{
_apiClient = apiClient;
}
/// <summary>
/// Method to get summary data
/// </summary>
/// <returns>summary Dto</returns>
public async Task<SummaryDto> GetSummary()
{
var response = await _apiClient.GetAsync("summary");
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
return JsonConvert.DeserializeObject<SummaryDto>(result);
return null;
}
}
and inside startup file:
services.AddHttpClient<ApiClient>((sp, config) =>
{
config.BaseAddress = new Uri(Configuration["ServiceBaseUrl"]);
config.DefaultRequestHeaders.Accept.Clear();
config.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
});
My question is how to add servercertificatecustomvalidationcallback
Upvotes: 0
Views: 850
Reputation: 1924
You can achieve it like this in .NET Core.
In Startup.cs
services.AddHttpClient<ApiClient>((sp, config) =>
{
config.BaseAddress = new Uri(Configuration["ServiceBaseUrl"]);
config.DefaultRequestHeaders.Accept.Clear();
config.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
{
//Your Validation Logic Here
return true; //OR false;
}
});
Upvotes: 1