如何从.net核心中的appsettings.json中提取列表 [英] How to extract a list from appsettings.json in .net core

查看:213
本文介绍了如何从.net核心中的appsettings.json中提取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

推荐答案

您可以使用Configuration绑定程序来获得配置源的强类型表示。

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核心中的appsettings.json中提取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆