ASP.NET Core Get Json Array using IConfiguration

后端 未结 14 2101
失恋的感觉
失恋的感觉 2020-11-30 21:49

In appsettings.json

{
      \"MyArray\": [
          \"str1\",
          \"str2\",
          \"str3\"
      ]
}

In Startup.cs

14条回答
  •  [愿得一人]
    2020-11-30 22:04

    If you want to pick value of first item then you should do like this-

    var item0 = _config.GetSection("MyArray:0");
    

    If you want to pick value of entire array then you should do like this-

    IConfigurationSection myArraySection = _config.GetSection("MyArray");
    var itemArray = myArraySection.AsEnumerable();
    

    Ideally, you should consider using options pattern suggested by official documentation. This will give you more benefits.

提交回复
热议问题