ASP.NET Core Get Json Array using IConfiguration

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

In appsettings.json

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

In Startup.cs

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 22:05

    Kind of an old question, but I can give an answer updated for .NET Core 2.1 with C# 7 standards. Say I have a listing only in appsettings.Development.json such as:

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

    I can extract them anywhere that the Microsoft.Extensions.Configuration.IConfiguration is implemented and wired up like so:

    var testUsers = Configuration.GetSection("TestUsers")
       .GetChildren()
       .ToList()
        //Named tuple returns, new in C# 7
       .Select(x => 
             (
              x.GetValue("UserName"), 
              x.GetValue("Email"), 
              x.GetValue("Password")
              )
        )
        .ToList<(string UserName, string Email, string Password)>();
    

    Now I have a list of a well typed object that is well typed. If I go testUsers.First(), Visual Studio should now show options for the 'UserName', 'Email', and 'Password'.

提交回复
热议问题