6.21SSL 证书配置
使用 HttpClient 发起 HTTPS 请求时,如果需要配置自定义的 SSL/TLS 证书,通常涉及到使用 HttpClientHandler 类,并通过 ServerCertificateCustomValidationCallback 属性来指定一个回调方法,该方法用于验证服务器的证书。如果需要使用客户端证书
使用 HttpClient 发起 HTTPS 请求时,如果需要配置自定义的 SSL/TLS 证书,通常涉及到使用 HttpClientHandler 类,并通过 ServerCertificateCustomValidationCallback 属性来指定一个回调方法,该方法用于验证服务器的证书。如果需要使用客户端证书,可以通过 HttpClientHandler.ClientCertificates 属性添加。
客户端证书认证#
services.AddHttpClient(string.Empty, client => {}) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ClientCertificates = { X509CertificateLoader.LoadPkcs12FromFile("path/to/client_certificate.pfx", "password") } });自定义服务器证书验证#
如果您需要自定义服务器证书的验证逻辑,可以设置 ServerCertificateCustomValidationCallback 属性:
services.AddHttpClient(string.Empty, client => {}) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { // 如果证书是预期的自签名证书,则接受它 if (cert.Subject == "CN=YourExpectedSubject") { return true; // 接受证书 } // 否则,使用默认的验证逻辑 return errors == System.Net.Security.SslPolicyErrors.None; } });忽略 SSL 证书验证#
除了配置 SSL 证书,您还可以通过添加以下配置来忽略 SSL 证书验证:
// 默认客户端配置services.AddHttpClient(string.Empty) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { // 忽略 SSL 证书验证 ServerCertificateCustomValidationCallback = HttpRemoteUtility.IgnoreSslErrors, SslProtocols = HttpRemoteUtility.AllSslProtocols });// 若使用 SocketsHttpHandler,可以通过以下配置来忽略 SSL 证书验证services.AddHttpClient(string.Empty) .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler() { SslOptions = new SslClientAuthenticationOptions { // 忽略 SSL 证书验证 RemoteCertificateValidationCallback = HttpRemoteUtility.IgnoreSocketSslErrors, EnabledSslProtocols = HttpRemoteUtility.AllSslProtocols }, });单次请求设置 SSL 证书#
除了可以在全局配置中 SSL 证书验证外,您还可以通过 SetHttpClientProvider 方法为单次请求单独设置 SSL 证书。示例代码如下:
HttpRequestBuilder.Get("https://furion.net/") .SetHttpClientProvider(() => (new HttpClient(new HttpClientHandler { // 忽略 SSL 证书验证 ServerCertificateCustomValidationCallback = HttpRemoteUtility.IgnoreSslErrors, SslProtocols = HttpRemoteUtility.AllSslProtocols }), client => client.Dispose()));