You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 22.04 LTS上ASP.NET Core Web API握手失败问题求助

解决ASP.NET Core API部署Ubuntu后外部访问触发SQL Server SSL握手失败问题

问题背景

ASP.NET Core Web API在Windows运行正常,部署到Ubuntu 22.04 LTS后,本地通过localhost:5169访问正常,但外部客户端(Windows/安卓)访问时,API连接SQL Server抛出SSL握手失败异常:

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database '****' on server '******'.
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type '****.ApiContext.apiContext'.
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)
System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream........

解决方案

1. 修正.NET Core的TLS配置(替代ServicePointManager)

.NET Core中ServicePointManager兼容性有限,推荐使用AppContext开关配置SQL Client的TLS行为,在Program.cs最开头添加:

// 强制使用托管网络栈(Linux环境下更稳定)
AppContext.SetSwitch("Microsoft.Data.SqlClient.UseManagedNetworkingOnLinux", true);
// 明确指定仅使用TLS 1.2(匹配SQL Server常见配置)
AppContext.SetSwitch("Microsoft.Data.SqlClient.EnableSslProtocols", "Tls12");

2. 优化SQL Server连接字符串

  • 移除无效配置:TrustServerCertificate=true在Encrypt=false时无意义,可删除
  • 确认Encrypt=false配置生效,修改后的连接字符串示例:
"ApiString": "Data Source=DB***;Initial Catalog=***;User Id=user;Password=*******;Connect Timeout=30;Encrypt=false;Persist Security Info=false;Application Intent=ReadWrite;MultiSubnetFailover=false"

3. 验证Ubuntu系统的TLS兼容性

检查系统能否与SQL Server正常建立TLS 1.2连接,替换<DB_SERVER>为你的数据库服务器地址后执行:

openssl s_client -connect <DB_SERVER>:1433 -tls1_2

若连接失败,更新OpenSSL修复系统TLS配置:

sudo apt update && sudo apt install --only-upgrade openssl

4. 检查SQL Server的外部访问权限

  • 确认SQL Server防火墙允许Ubuntu服务器IP访问1433端口
  • 在SQL Server配置管理器中启用TCP/IP协议

5. 调整API监听地址(确保外部可访问)

部署时确保API监听所有网卡地址,而非仅localhost,可在Program.cs中设置:

builder.WebHost.UseUrls("http://0.0.0.0:5169");

或通过启动命令指定:

dotnet YourApi.dll --urls "http://0.0.0.0:5169"

内容的提问来源于stack exchange,提问作者Dragon Slayer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:30:57