使用Windows身份验证连接到SQL Server

HAR*_*HNA 50 c# sql sql-server asp.net

当我尝试使用以下代码连接到SQL Server时:

SqlConnection con = new SqlConnection("Server=localhost,Authentication=Windows Authentication, Database=employeedetails");
con.Open();
SqlCommand cmd;
string s = "delete employee where empid=103";
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

建立与SQL Server的连接时发生与网络相关或特定于实例的错误.服务器未找到或无法访问.验证实例名称是否正确,以及SQL Server是否配置为允许远程连接.(提供程序:SQL网络接口,错误:25 - 连接字符串无效)

ps2*_*oat 56

SQL Server的连接字符串应该更像: "Server= localhost; Database= employeedetails; Integrated Security=True;"

如果您有一个SQL Server的命名实例,您还需要添加它,例如, "Server=localhost\sqlexpress"

  • 您的用户名看起来不正确。您的计算机名称是“ IIS APPPOOL”?您的用户名为“ ASP.NET V4.0”?请发布您的连接字符串,并使用实际的用户名和密码替换为“ xxxx”以掩盖该值。然后我们可以为您提供更好的帮助。 (2认同)
  • 您网站的应用程序池必须以某种帐户的身份工作,并且已作为登录名添加到SQL Server上,并且对数据库具有某些权限。“高级”设置中的“应用程序池”具有“身份”选项-您应在此处指定您的帐户。之后,您与“ Integrated Security = True”的连接必须正常工作。 (2认同)

Aja*_*y P 19

你的连接字符串是错误的

<connectionStrings>
   <add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)


mar*_*c_s 10

查看www.connectionstrings.com获取大量正确连接字符串的样本.

在您的情况下,使用此:

Server=localhost;Database=employeedetails;Integrated Security=SSPI
Run Code Online (Sandbox Code Playgroud)

更新:很明显,服务帐户用于运行ASP.NET Web应用程序不能访问到SQL Server,和,你可能会使用"匿名身份验证"您的网站从错误信息判断.

因此,您需要将此帐户添加IIS APPPOOL\ASP.NET V4.0为SQL Server登录名并将该登录名授予您的数据库,或者您需要切换到使用ASP.NET网站上的"Windows身份验证",以便调用Windows帐户到SQL Server并用作SQL Server上的登录.