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

MAUI Android无法连接SQL Server:预登录握手异常求助

.NET 7 Android 连接强制加密 SQL Server 预登录握手失败

问题详情

SQL Server配置强制加密,使用域自签名SSL证书,Android设备已安装对应CA证书。连接字符串如下:

"Server=FQDNofSqlServer; Database=xxx; User Id=sa; password=yyy;Encrypt=True;"

该连接在.NET 7桌面环境可正常建立加密连接,但.NET 7 Android环境触发以下异常:

Microsoft.Data.SqlClient.SqlException (0x80131904): 已成功与服务器建立连接,但预登录握手期间发生错误。(提供程序: TCP Provider, 错误: 35 - 捕获到内部异常)
---> System.Security.Authentication.AuthenticationException: 身份验证失败,请查看内部异常。
---> Interop+AndroidCrypto+SslException: 引发了类型为“Interop+AndroidCrypto+SslException”的异常。
--- 内部异常堆栈跟踪结束 ---
at System.Net.Security.SslStream.d__146`1[[System.Net.Security.SyncReadWriteAdapter, System.Net.Security, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]].MoveNext() 
at System.Net.Security.SslStream.AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions) 
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation) 
at Microsoft.Data.SqlClient.SNI.SNITCPHandle.EnableSsl(UInt32 options) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SNI\SNITcpHandle.cs:line 626 
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\src\Microsoft\Data\SqlClient\SqlInternalConnection.cs:line 776

此前在Xamarin的.NET Standard 2.1环境中可正常连接,当前为局域网场景,使用Web服务中转成本过高。

排查与解决方案

  • 确认Android证书安装方式:Android 11及以上版本安装用户证书时,需手动选择VPN和应用用途,否则应用无法读取该证书。重新安装CA证书时,确保选择正确的用途。
  • 配置Android网络安全策略:
    1. 在res/xml目录下新建network_security_config.xml,内容如下:
      <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
          <base-config>
              <trust-anchors>
                  <certificates src="system" />
                  <certificates src="user" />
              </trust-anchors>
          </base-config>
      </network-security-config>
      
    2. 在AndroidManifest.xml的application标签中添加引用:
      <application android:networkSecurityConfig="@xml/network_security_config">
          <!-- 其他配置 -->
      </application>
      
  • 调整连接字符串参数:
    1. 显式指定SSL协议:添加SslProtocol=Tls12(SQL Server通常支持TLS 1.2,避免协议不匹配)
    2. 确认Server字段与证书的CN/SAN字段完全一致,避免域名不匹配导致验证失败
  • 检查NuGet包版本:确保项目中使用的Microsoft.Data.SqlClient为最新稳定版,旧版本可能存在Android平台兼容性问题
  • 验证证书有效性:使用Android设备浏览器访问SQL Server的SSL端口(默认1433),确认证书能被正常识别,排除证书本身格式或配置问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:37:28