在ASP.NET应用程序中,您可以使用唯一的活动目录凭据连接到远程SQL Server。以下是一个示例代码,演示了如何使用Active Directory凭据连接到远程SQL Server。
using System;
using System.Configuration;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClass
{
public void ConnectToSQLServer()
{
// 获取Active Directory凭据
string activeDirectoryId = ConfigurationManager.AppSettings["ActiveDirectoryId"];
string activeDirectoryPassword = ConfigurationManager.AppSettings["ActiveDirectoryPassword"];
// 构建SQL Server连接字符串
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "your_server_name";
builder.InitialCatalog = "your_database_name";
builder.UserID = activeDirectoryId;
builder.Password = activeDirectoryPassword;
builder.Authentication = SqlAuthenticationMethod.ActiveDirectoryIntegrated;
// 创建SQL Server连接
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
try
{
// 打开连接
connection.Open();
// 执行SQL查询或其他操作
// ...
}
catch (SqlException ex)
{
// 处理连接错误
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
}
在上述代码中,您需要将your_server_name
替换为您的SQL Server实例的名称,将your_database_name
替换为您要连接的数据库的名称。
另外,您还需要在您的应用程序的配置文件(如web.config)中添加以下两个AppSettings配置项,以存储Active Directory凭据:
将your_active_directory_id
和your_active_directory_password
替换为您的Active Directory凭据。
通过以上步骤,您的ASP.NET应用程序将使用唯一的活动目录凭据来连接到远程SQL Server。