我有一个 .Net 8 中的 C# 应用程序,它使用实体框架连接到 SQL 数据库。我在连接字符串中使用 SQL 身份验证。在我的本地,我运行容器,我可以连接到 Azure SQL Server,一切都很好,但是当我使用完全相同的图像和环境变量在 Azure 容器实例内运行容器时,当我想要连接到确切的容器时,我会收到此错误我在本地连接的数据库相同。我将我的 Azure 容器实例公共 ID 和本地 ID 列入白名单。我还检查了“允许 Azure 服务和实例访问此服务器”。
在 Azure SQL Server 网络中,我设置:使用选定网络的公共网络访问,以防万一,我在防火墙规则中将“0.0.0.0”添加到“255.255.255.255”
Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HN1SVGHL7U9F", Request id "0HN1SVGHL7U9F:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)
---> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer.
---> System.Net.Sockets.SocketException (104): Connection reset by peer"
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)
您可以按照以下说明解决上述错误:
与
TrustServerCertificate=True
一起,将 Encrypt=False
添加到连接字符串。您可以使用下面的连接字符串:
Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<dbName>;Persist Security Info=False;User ID=<userName>;Password=<password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;
有时,Microsoft.Data.SqlClient 包可能存在问题。将其替换为 System.Data.SqlClient 包。
检查网络配置;如果网络不好的话,可能会出现上述错误。
欲了解更多信息,您可以参考这个MS问题。