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

如何在C#中读取Azure KeyVault引用配置?

问题分析与修复方案

核心问题

  1. 配置键名错误:代码中读取的键是ProdContoso:ST644,但实际配置的名称是ProdContoso:ST64,多了一个尾缀字符,导致无法匹配到目标配置项。
  2. 缺少KeyVault解析支持:仅通过AddEnvironmentVariables()加载配置,无法自动解析@Microsoft.KeyVault格式的引用,必须添加Azure KeyVault的配置提供者才能拉取实际密钥值。

修正后的代码

using Microsoft.Extensions.Configuration;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Security.KeyVault.Secrets;
using Azure.Identity;

public string GetKeyData()
{
    var config = new ConfigurationBuilder()
        .AddEnvironmentVariables()
        // 添加KeyVault配置提供者,用于解析并拉取密钥
        .AddAzureKeyVault(
            new Uri("https://contosokeyvault.vault.azure.net/"),
            new DefaultAzureCredential())
        .Build();

    // 使用正确的配置键名
    var key = config["ProdContoso:ST64"];
    Console.WriteLine($"ProdContoso:ST64:{key?.Substring(0, 5) ?? "null"}");
    return key;
}

必要准备

  • 安装相关NuGet包:
    • Microsoft.Extensions.Configuration.AzureKeyVault
    • Azure.Identity
  • 确保运行环境拥有访问目标KeyVault的权限(生产环境可使用托管身份,本地开发可通过Azure CLI登录授权)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:08:08