How to extract a list from appsettings.json in .net core

后端 未结 5 1889
耶瑟儿~
耶瑟儿~ 2020-12-24 00:13

I have an appsettings.json file which looks like this:

{
    \"someSetting\": {
        \"subSettings\": [
            \"one\",
            \"two\",
                 


        
5条回答
  •  梦毁少年i
    2020-12-24 01:00

    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
            {
                {"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();
            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]);
        }
    

    The important part is the call to Bind.

    The test and more examples are on GitHub

提交回复
热议问题