首页 > 解决方案 > .NET Core SqlException:an error occurred during the pre-login handshake

问题描述

I'm seeing an exception in Mac OS High Sierra (latest version) 10.13.5 when trying to connect to a MSSQL database using Entity Framework Core:

SqlException: 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)

I've updated to the latest version of .NET core:

dotnet --version: 2.1.300

dotnet --info: .NET Core SDK (reflecting any global.json):
 Version:   2.1.300
 Commit:    adab45bf0c

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.13
 OS Platform: Darwin
 RID:         osx.10.13-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.1.300/

Host (useful for support):
  Version: 2.1.0
  Commit:  caa7b7e2ba

.NET Core SDKs installed:
  1.0.4 [/usr/local/share/dotnet/sdk]
  2.0.0 [/usr/local/share/dotnet/sdk]
  2.1.300 [/usr/local/share/dotnet/sdk]

I've found a few similar exceptions after a quick google search, but nothing on the most recent version of OSX with the latest version of .NET core installed.

Is there a possibility this a bug in the latest version? I've tested on Windows with the same source code and had no issues.

Here are my references in the project file:

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.2" />
    <PackageReference Include="System.Security.Cryptography.OpenSsl" Version="4.5.0" />
  </ItemGroup>

标签: .net-coreentity-framework-core

解决方案


对于任何登陆这里以找到解决方案的人。以下是对我有用的解决方案。

环境

数据库: Microsoft SQL Server 2019 - 托管在 Amazon Web Services (AWS) 上

.Net Core: .Net Core SDK v3.1.401

操作系统:macOS Catalina 10.15.5 (19F101)

正在执行的操作

我试图通过以下命令迁移 EF Core 模型并更新数据库

dotnet ef migrations add initDBMigration --context myDBContext
dotnet ef database update

引发错误

与服务器成功建立连接,但在登录前握手期间发生错误。(提供者:SSL 提供者,错误:31 - 加密(ssl/tls)握手失败)

解决方案

主要问题是 AWS 通过其根证书使用 SSL 安全连接,并且 dotnet ef 工具无法验证或下载根证书。

所以需要手动下载安装证书并将TrustServerCertificate标记为true。

下载并安装根证书

  1. Goto使用 SSL/TLS 加密与数据库实例的连接
  2. 下载您所在地区的根证书,或者如果您不确定,请下载全球根证书(适用于所有地区)。全球根证书的直接链接(有效期至 2024 年 8 月 22 日星期四)
  3. 通过双击 .pem 文件(已下载)安装证书。您也可以通过“钥匙串访问”打开它
  4. 确保将“钥匙串:”选择为“系统”
  5. 单击“添加”以安装证书。

添加证书对话框

修改 SQL 连接字符串

  1. 导航到您的连接字符串
  2. 确保它有TrustServerCertificate=true

而已。现在再次执行相同的操作,它应该不会出现此错误。


推荐阅读