You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8中如何配置Azure SQL用户托管身份连接及连接字符串格式

.NET 8 配置用户托管身份连接Azure SQL Server

1. 连接字符串格式

用户托管身份对应的连接字符串无需包含密码,格式如下:

Server=tcp:{你的SQL服务器名称}.database.windows.net,1433;Database={你的数据库名称};Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Authentication=Active Directory Managed Identity;User Id={用户托管身份的Client ID}
  • 替换{你的SQL服务器名称}、{你的数据库名称}、{用户托管身份的Client ID}为实际值
  • Authentication=Active Directory Managed Identity指定使用托管身份认证
  • User Id参数是用户托管身份必需的(系统托管身份可省略),用于明确指定要使用的托管身份实例

2. EF Core 配置(Program.cs)

在Program.cs中配置DbContext时,直接使用上述连接字符串即可,EF Core会自动借助托管身份完成认证:

var builder = WebApplication.CreateBuilder(args);

// 配置DbContext
builder.Services.AddDbContext<YourDbContext>(options =>
{
    var connectionString = builder.Configuration.GetConnectionString("AzureSqlConnection");
    options.UseSqlServer(connectionString, sqlOptions =>
    {
        sqlOptions.EnableRetryOnFailure(); // 可选:启用重试机制提升稳定性
    });
});

// 其他中间件配置...

var app = builder.Build();
// 后续请求管道配置...
app.Run();

3. 额外验证

确保已完成以下前置操作:

  • 应用服务中启用的用户托管身份已被添加到Azure SQL Server的数据库用户中,并分配了合适的权限(如db_datareader、db_datawriter)
  • 应用服务的配置中已正确配置连接字符串(可在Azure门户的应用服务「配置」→「连接字符串」中设置,无需手动写入appsettings.json)

内容的提问来源于stack exchange,提问作者dna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 22:09:53