gpt4 book ai didi

c# - 模拟成功但数据库连接失败

转载 作者:行者123 更新时间:2023-11-30 17:04:48 25 4
gpt4 key购买 nike

我有这样的 C# (.NET 4.5) 代码(为演示而简化)用于连接到 SQL Server 2012 数据库:

public static void Test(WindowsIdentity ident)
{
using (WindowsImpersonationContext ctx = ident.Impersonate())
{
using (SqlConnection con = new SqlConnection("Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=False;Integrated Security=SSPI;Network Library=dbmssocn"))
{
con.Open();
}
ctx.Undo();
}
}

Open() 方法每次都会抛出以下异常:

System.Data.SqlClient.SqlException (0x80131904): 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: 0 - No connection could be made because the target machine actively refused it.)

模拟成功,因为如果我像这样添加跟踪:

public static void Test(WindowsIdentity ident)
{
using (TextWriterTraceListener listener = new TextWriterTraceListener(@"C:\temp\trace.log"))
{
using (WindowsImpersonationContext ctx = ident.Impersonate())
{
listener.WriteLine("Impersonated");
using (SqlConnection con = new SqlConnection("Data Source=MyServer,MyPort;Initial Catalog=MyDatabase;Persist Security Info=False;Integrated Security=SSPI;Network Library=dbmssocn"))
{
listener.WriteLine("About to open connection; WindowsIdentity.GetCurrent().Name = " + WindowsIdentity.GetCurrent().Name);
con.Open();
}
ctx.Undo();
listener.WriteLine("Impersonation undone");
}
}
}

我明白了:

Impersonated
About to open connection; WindowsIdentity.GetCurrent().Name = MyDomain\MyUser

如果我将完全相同的连接字符串放入 .udl 文件中,在同一台机器上以相同的“MyDomain\MyUser”帐户运行它,然后单击“测试连接”,它会成功。既然如此,我只是看不出问题可能是防火墙或任何类似性质的问题。有谁知道可能出了什么问题?我无权登录数据库服务器本身,因此此时无法检查其事件日志(等)。

最佳答案

您的问题来自连接字符串。连接字符串中的“Network Library = dbmssocn”将使客户端尝试在 UDP 端口 1434 而不是 TCP 端口 1433 上连接到 SQL 服务器。您删除“Network Library = dbmssocn"从您的应用程序的连接字符串应用程序将成功连接到 SQL 服务器。

关于c# - 模拟成功但数据库连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17117880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com