ASP.NET Core 6 Web API部署后SSL连接建立失败,求助解决方案
我开发了一个API,本地测试运行正常,但部署到服务器后调用该API时出现以下错误:
The SSL connection could not be established, see inner exception
内部异常信息如下:
System.Security.Authentication.AuthenticationException: Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'.
System.ComponentModel.Win32Exception (0x80090326): Mensaje recibido inesperado, o bien su formato es incorrecto.
--- End of inner exception stack trace ---
at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken)
控制器代码如下:
[HttpGet] [Route("obtienerespuesta")] public async Task<List<ResponsePymeModels>> InboundTransfersItauPyme(string api_key, string AccountLink, string AccountNumber, string urlbanco, string BookingDate) { var serviceCollection = new ServiceCollection(); Configuere(serviceCollection); var servicios = serviceCollection.BuildServiceProvider(); var httpClientFactory = servicios.GetRequiredService<IHttpClientFactory>(); var client = httpClientFactory.CreateClient(); client.Timeout = TimeSpan.FromMinutes(230); client.DefaultRequestHeaders.Add("x-api-key", api_key); var json = new JObject( new JProperty("RequestData", new JObject( new JProperty("AccountCredential", new JObject( new JProperty("AccountLink", AccountLink) ) ), new JProperty("AccountNumber", AccountNumber), new JProperty("BookingDate", BookingDate), new JProperty("Currency", "CLP") ) ) ); var postData = new StringContent(json.ToString(), Encoding.UTF8, "application/json"); var request = await client.PostAsync(urlbanco, postData);//错误发生在此行 var response = await request.Content.ReadAsStringAsync(); // .......... // .......... } private static void Configuere(ServiceCollection services) { services.AddHttpClient(); }
可能的解决方向
1. 指定TLS版本
服务器的.NET运行环境可能默认启用的TLS版本过低(如TLS 1.0/1.1),而目标API仅支持TLS 1.2及以上版本。在创建HttpClient后添加以下代码强制指定TLS版本:
// 配置支持的TLS版本 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; // 确保HTTP版本与TLS兼容 client.DefaultRequestVersion = HttpVersion.Version11; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher;
2. 处理证书信任问题
服务器可能未信任目标API的SSL证书(比如目标使用自签名证书或内部CA颁发的证书):
- 生产环境:将目标API的根证书导入服务器的受信任根证书颁发机构存储中。
- 测试环境(不建议生产使用):可以配置HttpClient忽略证书验证,示例代码如下:
var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; var client = new HttpClient(handler);
如果使用IHttpClientFactory,可在注册时统一配置:
services.AddHttpClient("TrustAllCert") .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true });
之后通过名称创建客户端:var client = _httpClientFactory.CreateClient("TrustAllCert");
3. 修复HttpClient的错误使用方式
当前代码每次请求都重新创建ServiceCollection和ServiceProvider,属于低效且易出问题的实践。正确做法是在项目启动时注册HttpClient,通过依赖注入使用:
- 在
Program.cs中注册:
builder.Services.AddHttpClient();
- 在控制器中注入
IHttpClientFactory:
private readonly IHttpClientFactory _httpClientFactory; public YourController(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; }
- 在方法中直接使用注入的工厂创建客户端,移除原有
ServiceCollection相关代码。
4. 检查服务器网络策略
服务器的防火墙、代理或安全组可能阻止了TLS握手所需的通信:
- 确认服务器可以访问目标API的域名和443端口(HTTPS默认端口)。
- 检查代理是否需要配置SSL直通或开启特定TLS协议支持。
内容的提问来源于stack exchange,提问作者Carmen Cisterna Chamblas

