ASP.NET Core Get Json Array using IConfiguration

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

In appsettings.json

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

In Startup.cs

14条回答
  •  再見小時候
    2020-11-30 22:25

    If you have array of complex JSON objects like this:

    {
      "MySettings": {
        "MyValues": [
          { "Key": "Key1", "Value":  "Value1" },
          { "Key": "Key2", "Value":  "Value2" }
        ]
      }
    }
    

    You can retrieve settings this way:

    var valuesSection = configuration.GetSection("MySettings:MyValues");
    foreach (IConfigurationSection section in valuesSection.GetChildren())
    {
        var key = section.GetValue("Key");
        var value = section.GetValue("Value");
    }
    

提交回复
热议问题