如何配置Key Vault密钥值以填充Options模式的List<string>属性?
问题:Key Vault中配置列表类型密钥值以填充Options类的正确方式
我需要通过Options模式从Azure Key Vault中填充以下类:
public class TestOptions { public string Continent { get; set; } public List<string> Countries { get; set; } }
Key Vault中已创建以下密钥:
Test--Continent Test--Countries
通过以下代码加载TestOptions:
builder.Register(ctx => ctx.Resolve<IConfiguration>().GetSection("Test").Get<TestOptions>()).SingleInstance();
目前Continent属性能正常填充,但Countries始终为null。此前在appsettings.json中按如下配置时可正常工作:
"Test": { "Continent": "Europe", "Countries": [ "Germany", "France", "Spain" ] }
请问Key Vault中Test--Countries的密钥值应该如何设置?
解决方案
针对列表类型的配置项,Azure Key Vault支持两种有效的设置方式:
方式1:逗号分隔字符串(简单场景首选)
直接将Test--Countries的密钥值设置为逗号分隔的字符串,示例值:
Germany,France,Spain
.NET配置系统会自动将这种格式解析为List<string>类型,无需额外配置。
方式2:索引式密钥命名(复杂场景适用)
如果列表项包含逗号等特殊字符,推荐创建多个带索引的密钥,命名规则为Test--Countries--[索引序号],比如:
Test--Countries--0 = Germany Test--Countries--1 = France Test--Countries--2 = Spain
配置系统会自动将这些索引化的密钥合并为一个完整的List<string>,正确填充Countries属性。
内容的提问来源于stack exchange,提问作者Xile
相关产品推荐
相关产品推荐

