ASP.NET Core Get Json Array using IConfiguration

后端 未结 14 1981
失恋的感觉
失恋的感觉 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<string>("UserName"),
                            Email = x.GetValue<string>("Email"),
                            Password = x.GetValue<string>("Password")
                        });
    
        return new { Data = testUsers };
    }
    
    0 讨论(0)
  • 2020-11-30 22:01

    This worked for me to return an array of strings from my config:

    var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
        .Get<string[]>();
    

    My configuration section looks like this:

    "AppSettings": {
        "CORS-Settings": {
            "Allow-Origins": [ "http://localhost:8000" ],
            "Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
        }
    }
    
    0 讨论(0)
  • 2020-11-30 22:03

    appsettings.json:

    "MySetting": {
      "MyValues": [
        "C#",
        "ASP.NET",
        "SQL"
      ]
    },
    

    MySetting class:

    namespace AspNetCore.API.Models
    {
        public class MySetting : IMySetting
        {
            public string[] MyValues { get; set; }
        }
    
        public interface IMySetting
        {
            string[] MyValues { get; set; }
        }
    }
    

    Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.Configure<MySetting>(Configuration.GetSection(nameof(MySetting)));
        services.AddSingleton<IMySetting>(sp => sp.GetRequiredService<IOptions<MySetting>>().Value);
        ...
    }
    

    Controller.cs

    public class DynamicController : ControllerBase
    {
        private readonly IMySetting _mySetting;
    
        public DynamicController(IMySetting mySetting)
        {
            this._mySetting = mySetting;
        }
    }
    

    Access values:

    var myValues = this._mySetting.MyValues;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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<string>("UserName"), 
              x.GetValue<string>("Email"), 
              x.GetValue<string>("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'.

    0 讨论(0)
  • 2020-11-30 22:08

    Short form:

    var myArray= configuration.GetSection("MyArray")
                            .AsEnumerable()
                            .Where(p => p.Value != null)
                            .Select(p => p.Value)
                            .ToArray();
    

    It returns an array of string:

    {"str1","str2","str3"}

    0 讨论(0)
提交回复
热议问题