时间:2021-07-01 10:21:17 帮助过:36人阅读
最近在一个ASP.NET Core站点中遇到一个奇怪问题。当用dotnet run命令启动站点后,开始的一段时间请求执行速度超慢,有时要超过20秒,有时甚至超过1分钟,日志中会记录这样的错误:
System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
当这些执行超慢的请求执行完成后(只是超慢,但没有出现500错误),一切就恢复正常,上面的错误日志也不再出现。
更奇怪的是这个问题只在Linux服务器上出现,在Windows服务器上不会出现。
在园子里看到“.NET Core中ADO.NET SqlClient的使用与常见问题”博文后,我们怀疑可能是SQL Server数据库服务器没有安装SP3(我们用的是阿里云RDS)。
这个问题,表象上体现的是一个连接超时的错误:
Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 35 - An internal exception was caught) ---> System.AggregateException: One or more errors occurred. (No such device or address) ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address
但是这个错误却是因为SQL Server的版本问题造成的,.NET Core中的SqlClient能支持的SQL Server最小版本为 SQL Server 2008 R2 SP3,如果你的数据库小于这个版本,就会出现这个异常。
官方的Issues在此:https://github.com/dotnet/corefx/issues/9719
今天晚上突然想到,会不会是数据库连接字符串写法的问题,换一种写法试试。于是将connection string由
"Data Source=server-name;initial Catalog=database-name;user=username;password=password"
改为
"Server=server-name;Database=database-name;user=username;password=password"
之后,问题就神奇地解决了!
.NET跨平台之旅:数据库连接字符串写法引发的问题
标签:not options dso exception https while handle 速度 blog