6.52Configuring SSL Certificates
When using HttpClient to make HTTPS requests, if you need to configure a custom SSL/TLS certificate, this typically involves using the HttpClientHandler class and specifying a callback method through the ServerCertificateCustomValidationCallback property to validate the server's certificate. If you need to use a client certificate, you can add it through the HttpClientHandler.ClientCertificates property.
Client Certificate Authentication
services.AddHttpClient(string.Empty, client => {}) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ClientCertificates = { X509CertificateLoader.LoadPkcs12FromFile("path/to/client_certificate.pfx", "password") } });Custom Server Certificate Validation
If you need to customize the server certificate validation logic, you can set the ServerCertificateCustomValidationCallback property:
services.AddHttpClient(string.Empty, client => {}) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { // If the certificate is the expected self-signed certificate, accept it if (cert.Subject == "CN=YourExpectedSubject") { return true; // Accept the certificate } // Otherwise, use the default validation logic return errors == System.Net.Security.SslPolicyErrors.None; } });Ignoring SSL Certificate Validation
In addition to configuring SSL certificates, you can also ignore SSL certificate validation by adding the following configuration:
// Default client configurationservices.AddHttpClient(string.Empty) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { // Ignore SSL certificate validation ServerCertificateCustomValidationCallback = HttpRemoteUtility.IgnoreSslErrors, SslProtocols = HttpRemoteUtility.AllSslProtocols });// If using SocketsHttpHandler, you can ignore SSL certificate validation with the following configurationservices.AddHttpClient(string.Empty) .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler() { SslOptions = new SslClientAuthenticationOptions { // Ignore SSL certificate validation RemoteCertificateValidationCallback = HttpRemoteUtility.IgnoreSocketSslErrors, EnabledSslProtocols = HttpRemoteUtility.AllSslProtocols }, });Setting the SSL Certificate for a Single Request
In addition to validating SSL certificates in global configuration, you can also set the SSL certificate for a single request using the SetHttpClientProvider method. The sample code is as follows:
HttpRequestBuilder.Get("https://furion.net/") .SetHttpClientProvider(() => (new HttpClient(new HttpClientHandler { // Ignore SSL certificate validation ServerCertificateCustomValidationCallback = HttpRemoteUtility.IgnoreSslErrors, SslProtocols = HttpRemoteUtility.AllSslProtocols }), client => client.Dispose()));