I have a problem with a connect from my asp.net core 2.2 project to an https site like there. I use IHttpClientFactory to create typed HttpClient in Startup.cs
services.AddHttpClient<ICustomService, MyCustomService>();
And I don't understand, how can I ignore SSL connection problems without creating HttpClient manually like this
using (var customHandler = new HttpClientHandler())
{
customHandler.ServerCertificateCustomValidationCallback = (m, c, ch, e) => { return true; };
using (var customClient = new HttpClient(customHandler)
{
// my code
}
}
To bypass SSL certificate validation for local and test servers, you can pass the -k or --insecure option to the Curl command. This option explicitly tells Curl to perform "insecure" SSL connections and file transfers. Curl will ignore any security warnings about an invalid SSL certificate and accept it as valid.
ConfigurePrimaryHttpMessageHandler(IHttpClientBuilder, Func<IServiceProvider,HttpMessageHandler>) Adds a delegate that will be used to configure the primary HttpMessageHandler for a named HttpClient.
The HttpClient now will not throw any SSL validation errors. This approach is actually more flexible because you can control the validation - you can have some requests that you want validated and others that you do not. In this case you create a second HttpClient the usual way without the handler - that one’s requests will always be validated.
But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood. There are many other benefits of IHttpClientFactory like Resilient HttpClient using polly, but that is not in scope of this article.
HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood. There are many other benefits of IHttpClientFactory like Resilient HttpClient using polly, but that is not in scope of this article.
Using Certificate Authentication with IHttpClientFactory and HttpClient In the following example, a client certificate is added to a HttpClientHandler using the ClientCertificates property from the handler. This handler can then be used in a named instance of a HttpClient using the ConfigurePrimaryHttpMessageHandler method.
Use ConfigureHttpMessageHandlerBuilder
:
services.AddHttpClient<ICustomService, MyCustomService>()
.ConfigureHttpMessageHandlerBuilder(builder =>
{
builder.PrimaryHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (m, c, ch, e) => true
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With