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

如何在C#中通过Azure Key Vault检索相似名称的多个密钥?

解决方案

核心思路:利用密钥名称前缀筛选

Azure Key Vault的官方SDK(Azure.Security.KeyVault.Keys)支持通过前缀过滤来获取名称匹配的密钥,无需拉取全部密钥条目。针对你的场景,所有对应单台PC的密钥都以PC1-这类前缀开头,正好可以用这个方式快速筛选。

具体实现步骤

  1. 安装必要NuGet包
    确保项目中引用最新的Azure Key Vault密钥库和身份验证包:
Install-Package Azure.Security.KeyVault.Keys
Install-Package Azure.Identity
  1. 编写C#代码实现前缀筛选
    使用KeyClient结合GetKeysOptions.Prefix属性指定筛选前缀,异步获取匹配的密钥:
using Azure.Identity;
using Azure.Security.KeyVault.Keys;

// 初始化KeyClient
string vaultUrl = "https://your-key-vault-name.vault.azure.net/";
var client = new KeyClient(new Uri(vaultUrl), new DefaultAzureCredential());

// 设置筛选前缀,比如针对PC1的密钥
var options = new GetKeysOptions { Prefix = "PC1-" };

// 异步遍历获取所有匹配的密钥
await foreach (KeyProperties key in client.GetKeysAsync(options))
{
    Console.WriteLine($"密钥名称: {key.Name}");
    // 如需获取密钥的具体值,可调用client.GetKeyAsync(key.Name)
    var keyBundle = await client.GetKeyAsync(key.Name);
    Console.WriteLine($"密钥值信息: {keyBundle.Value.Key}");
}

关键说明

  • 前缀筛选是Azure Key Vault服务端支持的功能,只会返回符合前缀条件的密钥,大幅减少数据传输量和耗时。
  • 代码中使用DefaultAzureCredential进行身份验证,适用于本地开发、Azure托管环境等多种场景,你也可以根据实际需求替换为其他凭据类型(比如ClientSecretCredential)。
  • 如果需要获取密钥的具体值(而非仅元数据),在遍历到匹配的KeyProperties后,调用GetKeyAsync即可单独获取该密钥的完整信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 07:35:06