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

如何从Azure Key Vault读取整个配置节?

从Azure Key Vault读取完整配置节的解决方案

问题原因

Azure Key Vault中的密钥是扁平存储的,默认配置提供者不会自动将带--分隔符的密钥名称(如Section--Secret1)映射为层级化的配置节。虽然可以通过Configuration["Section:Secret1"]读取单个密钥,但直接读取Configuration["Section"]会返回null——因为配置系统未将这些扁平密钥自动组装成完整的节节点。

解决方法

方法1:自定义密钥名称映射(推荐)

通过自定义KeyVaultSecretManager,将密钥名称中的--替换为配置系统默认的层级分隔符:,让配置系统自动识别并组装层级化的配置节。

  1. 实现自定义密钥管理器:
public class CustomKeyVaultSecretManager : KeyVaultSecretManager
{
    // 可选:仅加载包含--分隔符的密钥,按需调整
    public override bool Load(SecretProperties secret)
    {
        return secret.Name.Contains("--");
    }

    // 将密钥名称中的--替换为配置系统的层级分隔符
    public override string GetKey(KeyVaultSecret secret)
    {
        return secret.Name.Replace("--", ConfigurationPath.KeyDelimiter);
    }
}
  1. 在配置中使用自定义管理器:
var builder = WebApplication.CreateBuilder(args);

// 添加Azure Key Vault配置并使用自定义管理器
builder.Configuration.AddAzureKeyVault(
    new Uri("https://your-key-vault-name.vault.azure.net/"),
    new DefaultAzureCredential(),
    new CustomKeyVaultSecretManager());

// 现在可以直接读取完整配置节
var section = builder.Configuration.GetSection("Section");
// 也可以绑定到强类型对象
var sectionSettings = section.Get<YourSectionSettingsModel>();

完成配置后,Configuration.GetSection("Section")会返回包含所有子密钥的完整节,无需逐个读取单个密钥。

方法2:手动筛选组装配置节

如果不想修改配置提供者,也可以手动从配置集合中筛选目标节的所有密钥,组装成字典或强类型对象:

// 筛选所有以"Section:"开头的配置项
var sectionItems = builder.Configuration.AsEnumerable()
    .Where(kv => kv.Key.StartsWith("Section:"))
    .ToDictionary(
        kv => kv.Key.Substring("Section:".Length), 
        kv => kv.Value
    );

// 转换为强类型对象(需引入Microsoft.Extensions.Configuration.Binder包)
var sectionSettings = sectionItems.ToObject<YourSectionSettingsModel>();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:17:20