[2024-05-13 13:48:10 ERR] [Microsoft.EntityFrameworkCore.Database.Connection] An error occurred using the connection to database 'Demo' on server '127.0.0.1'. [2024-05-13 13:48:10 ERR] [Microsoft.EntityFrameworkCore.Query] An exception occurred while iterating over the results of a query for context type 'DemoDbContext'. 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.
以前也遇到過類似的問題,是
在github上提了個
Encrypt=False,若SQL Server配置了強制使用加密連接也會取嘗試建立加密連接
失敗原因是SQL Server的證書沒有在客戶端通過校驗。下面是本機進行復現的錯誤信息:
那麼解決方案有以下幾種:
-
給SQL Server安裝正確的證書
-
在連接字符串中添加
TrustServerCertificate=True
-
連接字符串中設置
Encrypt=False
關於Encrypt
和TrustServerCertificate
參數,可參考:
Encrypt connection string/attribute | Trust Server Certificate connection string/attribute | Result |
---|---|---|
No/Optional | Ignored | No encryption occurs. |
Yes/Mandatory | No | Encryption occurs only if there's a verifiable server certificate, otherwise the connection attempt fails. |
Yes/Mandatory | Yes | Encryption always occurs, but may use a self-signed server certificate. |
Strict1 | Ignored | Encryption always occurs and must use a verifiable server certificate, otherwise the connection attempt fails. |
小結
結合本次及之前遇到的問題,SQL Server連接報錯,有以下幾種原因:
-
客戶端/服務端間TLS版本不兼容
-
服務器證書有問題,客戶端校驗不通過
最後附一張
參考資料