我面临着一个非常奇怪的问题。给出下面的代码:
static void Main()
{
var c = new System.Data.SqlClient.SqlConnection();
c.ConnectionString = "Data Source=SOME_NAME;Initial Catalog=SOME_DB;Integrated Security=True";
c.ConnectionString = ""; //null also triggers exception
Console.WriteLine("Success");
}
它一直运行良好,但在最新版本的Windows 10(1803)上,该版本具有.NET Version 4.7.03056 Release 461808(似乎是4.7.2),它会出现以下异常而崩溃:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.SqlClient.SqlConnection.CacheConnectionStringProperties()
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at TestCacheConnectionStringProperties.Program.Main()
如果我删除ConnectionString
的任何赋值语句,第二个赋值就会崩溃。
我查看了源代码,没有找到可能导致NullReferenceException
的地方(然而源代码似乎是针对.NET Framework 4.7.1的,所以可能有所改变)。
现在的问题是 - 是什么导致了这个问题?这是.NET的一个bug吗?如果是 - 如何解决它?
更新:根据评论 - 非常感谢大家 - 问题是由这些行引起的(反编译):
private void CacheConnectionStringProperties()
{
SqlConnectionString connectionOptions = this.ConnectionOptions as SqlConnectionString;
if (connectionOptions != null)
this._connectRetryCount = connectionOptions.ConnectRetryCount;
//Seems like this is causing the bug because it is not inside of null-check-if for connectionOptions variable
if (this._connectRetryCount != 1 || !ADP.IsAzureSqlServerEndpoint(connectionOptions.DataSource))
return;
this._connectRetryCount = 2;
}
它与Azure有一定关系,与现有资源不太相同。
我在这里发布了该问题,并等待回复。
CacheConnectionStringProperties
的一个漏洞,可能只存在于某些版本中。我反编译了4.7.3056.0
程序集并发现一个调用ADP.IsAzureSqlServerEndpoint(sqlConnectionString.DataSource)
的语句,但它不应该位于检查sqlConnectionString
是否为null
之外。然而,我在这里找不到这段代码(https://github.com/dotnet/corefx/blob/master/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs/#L104)。所以我不确定这些代码来自何处。 - Jeroen MostertTwitter
错误跟踪器。 - Panagiotis Kanavosif (this._connectRetryCount == 1 && ADP.IsAzureSqlServerEndpoint(connectionOptions.DataSource)) { this._connectRetryCount = 2; }
在 null 检查块之后。如果connectionOptions
为空,则会抛出 NRE 异常。 - Panagiotis Kanavos