问题描述
我有一个 appsettings.json 文件,如下所示:
I have an appsettings.json file which looks like this:
{
"someSetting": {
"subSettings": [
"one",
"two",
"three"
]
}
}
当我构建我的配置根目录并执行诸如 config["someSetting:subSettings"]
之类的操作时,它返回 null 并且可用的实际设置如下所示:
When I build my configuration root, and do something like config["someSetting:subSettings"]
it returns null and the actual settings available are something like this:
config["someSettings:subSettings:0"]
是否有更好的方法将 someSettings:subSettings
的内容检索为列表?
Is there a better way of retrieving the contents of someSettings:subSettings
as a list?
推荐答案
您可以使用配置绑定器来获取配置源的强类型表示.
You can use the Configuration binder to get a strong type representation of the configuration sources.
这是我之前写的一个测试的例子,希望对你有帮助:
This is an example from a test that I wrote before, hope it helps:
[Fact]
public void BindList()
{
var input = new Dictionary<string, string>
{
{"StringList:0", "val0"},
{"StringList:1", "val1"},
{"StringList:2", "val2"},
{"StringList:x", "valx"}
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(input);
var config = configurationBuilder.Build();
var list = new List<string>();
config.GetSection("StringList").Bind(list);
Assert.Equal(4, list.Count);
Assert.Equal("val0", list[0]);
Assert.Equal("val1", list[1]);
Assert.Equal("val2", list[2]);
Assert.Equal("valx", list[3]);
}
重要的部分是调用Bind
.
测试和更多示例位于 GitHub
这篇关于如何从 .net core 中的 appsettings.json 中提取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!