如何从.net核心中的appsettings.json中提取列表

dev*_*ife 47 c# .net-core asp.net-core

我有一个appsettings.json文件,如下所示:

{
    "someSetting": {
        "subSettings": [
            "one",
            "two",
            "three"
         ]
    }
}
Run Code Online (Sandbox Code Playgroud)

当我构建我的配置根,并做类似的config["someSetting:subSettings"]事情返回null并且可用的实际设置是这样的:

config["someSettings:subSettings:0"]

有没有更好的方法来检索someSettings:subSettings列表的内容?

Kir*_*man 104

假设你appsettings.json看起来像这样:

{
  "foo": {
    "bar": [
      "1",
      "2",
      "3"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样提取列表项:

Configuration.GetSection("foo:bar").Get<List<string>>()
Run Code Online (Sandbox Code Playgroud)

  • 方式简单,人性可读,接受的答案! (9认同)
  • 这对我有用,但我必须首先安装"Microsoft.Extensions.Configuration.Binder"NuGet包,如[here](/sf/answers/3257918961/)所述. (4认同)

Vic*_*aci 30

您可以使用配置绑定器获取配置源的强类型表示.

这是我之前写过的测试的一个例子,希望它有所帮助:

    [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]);
    }
Run Code Online (Sandbox Code Playgroud)

重要的是呼吁Bind.

测试和更多示例在GitHub上

  • 任何提示如何使用`services.Configure &lt;TOptions&gt;`做到这一点?我想从包含数组的配置字段中注入选项 (2认同)

小智 7

var settingsSection = config.GetSection["someSettings:subSettings"];
var subSettings = new List<string>;

foreach (var section in settingsSection.GetChildren())
{
    subSettings.Add(section.Value);
}
Run Code Online (Sandbox Code Playgroud)

这应该给你你需要的值,存储在 subSettings

为提出半旧线程而道歉。我很难找到答案,因为不推荐使用大量方法,例如GetGetValue。如果您只需要一个没有配置绑定器的简单解决方案,这应该没问题。:)


MiF*_*vil 7

以我为例配置

 services.Configure<List<ApiKey>>(Configuration.GetSection("ApiKeysList"));
Run Code Online (Sandbox Code Playgroud)

未加载,因为属性是只读的并且没有默认构造函数

在其他情况下,类具有公共字段而不是属性。

//不工作

  public class ApiKey : IApiKey
    {
        public ApiKey(string key, string owner)
        {
            Key = key;
            OwnerName = owner;
        }
        public string Key { get;  }
        public string OwnerName { get;}
    } 
Run Code Online (Sandbox Code Playgroud)

//在职的

    public class ApiKey : IApiKey
    {
        public ApiKey(){}//Added default constructor
        public ApiKey(string key, string owner)
        {
            Key = key;
            OwnerName = owner;
        }
        public string Key { get; set; }        //Added set property
        public string OwnerName { get; set; }  //Added set property
    } 
Run Code Online (Sandbox Code Playgroud)


Hel*_*ate 5

在.NetCore中,这就是我所做的:

在您的appsettings.json中,为您的自定义定义创建一个配置部分:

"Definitions": {
  "Defined": [
    {
      "Name": "somename",
      "Title": "sometitle",
      "Image": "some image url"
    },
    {
      "Name": "anothername",
      "Title": "anothertitle",
      "Image": "another image url"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

创建一个类来建模对象:

public class Defined
{
    public string Name { get; set; }
    public string Title { get; set; }
    public string Image { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在您的启动-> ConfigureServices中

services.Configure<List<Defined>>(Configuration.GetSection("Definitions:Defined"));

然后在您的控制器中,如下所示:

Public class AccountController: Controller
{
    private readonly IOptions<List<Defined>> _customClients;
    public AccountController(IOptions<List<Defined>> customClients)
    {
        _customClient = customClients;
    }
  ...
}
Run Code Online (Sandbox Code Playgroud)

就像一个例子,我在上面的控制器的其他地方使用了它,如下所示:

       _customClients.Value.ForEach(x => {
            // do something with x
        });
Run Code Online (Sandbox Code Playgroud)