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

Blazor混合应用中结合环境变量使用Azure Key Vault的正确方式

Blazor混合应用结合环境变量使用Azure Key Vault的正确配置方式

核心思路

利用.NET的配置优先级机制和环境条件判断,让开发环境自动读取本地连接串,测试/生产环境自动加载Azure Key Vault中的配置,全程无需手动注释代码。

具体配置步骤

1. 调整配置文件结构

  • appsettings.json:仅保留通用配置项,移除Key Vault相关引用:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
  • appsettings.Development.json:保留本地数据库连接串,专供开发环境使用:
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=MY_LOCAL_SERVER\\SQLEXPRESS;..."
  },
  "DetailedErrors": true,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Microsoft.AspNetCore.SignalR": "Debug"
    }
  }
}
  • appsettings.Staging.json(新增测试环境配置文件):添加Key Vault的配置引用:
{
  "ConnectionStrings": {
    "DefaultConnection": "@AzureKeyVault(ConnectionStrings--DefaultConnection)"
  }
}

2. 修改Program.cs的Key Vault加载逻辑

通过环境标识和环境变量判断,仅在非开发环境且配置了Vault地址时,才加载Azure Key Vault:

var builder = WebApplication.CreateBuilder(args);

// 仅在非开发环境、且配置了VaultUri时加载Azure Key Vault
var vaultUri = Environment.GetEnvironmentVariable("VaultUri");
if (!builder.Environment.IsDevelopment() && !string.IsNullOrEmpty(vaultUri))
{
    builder.Configuration.AddAzureKeyVault(new Uri(vaultUri), new DefaultAzureCredential());
}

// 后续服务注册代码保持不变
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();

builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, PersistingRevalidatingAuthenticationStateProvider>();

builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = IdentityConstants.ApplicationScheme;
        options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    })
    .AddIdentityCookies();

var conn = builder.Configuration.GetConnectionString("DefaultConnection");
// ...后续数据库操作代码

3. 环境变量配置

  • 开发环境:无需设置VaultUri环境变量,或设为空值,代码会自动跳过Key Vault加载,直接读取本地配置文件中的连接串。
  • 测试/生产环境:设置VaultUri环境变量为你的Azure Key Vault地址,同时确保应用服务拥有访问Key Vault的权限(通过托管标识或服务主体配置);另外设置ASPNETCORE_ENVIRONMENT为Staging,让应用加载测试环境专属配置文件。

配置优先级说明

.NET配置系统的优先级从高到低为:环境变量 > 命令行参数 > 环境特定配置文件(如Staging) > 通用配置文件(appsettings.json)。测试环境中,Key Vault加载的连接串会覆盖配置文件中的引用;开发环境则直接使用本地配置,互不干扰。

额外注意事项

  • 确保Azure Key Vault中已创建名为ConnectionStrings--DefaultConnection的密钥,对应测试环境的数据库连接串。
  • 测试环境部署时,可通过Azure门户或CI/CD流水线批量设置环境变量,避免手动修改代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:43:20