ASP.NET Core Get Json Array using IConfiguration

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

In appsettings.json

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

In Startup.cs

14条回答
  •  粉色の甜心
    2020-11-30 22:00

    For the case of returning an array of complex JSON objects from configuration, I've adapted @djangojazz's answer to use anonymous types and dynamic rather than tuples.

    Given a settings section of:

    "TestUsers": [
    {
      "UserName": "TestUser",
      "Email": "Test@place.com",
      "Password": "P@ssw0rd!"
    },
    {
      "UserName": "TestUser2",
      "Email": "Test2@place.com",
      "Password": "P@ssw0rd!"
    }],
    

    You can return the object array this way:

    public dynamic GetTestUsers()
    {
        var testUsers = Configuration.GetSection("TestUsers")
                        .GetChildren()
                        .ToList()
                        .Select(x => new {
                            UserName = x.GetValue("UserName"),
                            Email = x.GetValue("Email"),
                            Password = x.GetValue("Password")
                        });
    
        return new { Data = testUsers };
    }
    

提交回复
热议问题