在appsettings.json

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

在Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IConfiguration>(Configuration);
}

在HomeController

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    public HomeController(IConfiguration config)
    {
        this._config = config;
    }
    
    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}

上面是我的代码。结果是零。 如何获取数组?


当前回答

如果你想要选择第一项的值,那么你应该这样做-

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

如果你想选择整个数组的值,那么你应该这样做-

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

理想情况下,您应该考虑使用官方文档建议的选项模式。这会给你带来更多的好处。

其他回答

设置。json文件:

{
    "AppSetting": {
        "ProfileDirectory": "C:/Users/",
        "Database": {
            "Port": 7002
        },
        "Backend": {
            "RunAsAdmin": true,
            "InstallAsService": true,
            "Urls": [
                "http://127.0.0.1:8000"
            ],
            "Port": 8000,
            "ServiceName": "xxxxx"
        }
    }
}

code

代码:

public static IConfigurationRoot GetConfigurationFromArgs(string[] args, string cfgDir)
{
    var builder = new ConfigurationBuilder()
            .SetBasePath(cfgDir)
            .AddCommandLine(args ?? new string[0]) // null  in UnitTest null will cause exception
            .AddJsonFile(Path.Combine(cfgDir, "setting.json"), optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
        // .AddInMemoryollection(configDictionary)
        ;
    var config = builder.Build();
    return config;
}

你可以使用services.AddOptions<AppSettingOption>("AppSetting")或者直接从iconfigationroot对象获取Object。

var cfg = GetConfigurationFromArgs(args, appDataDirectory);
cfg.GetSection("AppSetting").Get<AppSettingOption>()

输出:

{App.AppSettingOption}
    Backend: {App.BackendOption}
    Database: {App.DatabaseOption}
    ProfileDirectory: "C:/Users/"

你可以像这样使用Microsoft.Extensions.Configuration.Binder包:

在你的appsettings.json中

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

创建保存配置的对象:

 public class MyConfig
 {
     public List<string> MyArray { get; set; }
 }

在你的控制器绑定配置:

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    private readonly MyConfig _myConfig = new MyConfig();

    public HomeController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.Bind(_myConfig));
    }
}

您可以安装以下两个NuGet包:

using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.Configuration.Binder;

然后你将有可能使用以下扩展方法:

var myArray = _config.GetSection("MyArray").Get<string[]>();

对于从配置返回复杂JSON对象数组的情况,我调整了@djangojazz的答案,以使用匿名类型和动态而不是元组。

给定的设置部分:

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

你可以这样返回对象数组:

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 };
}

简式:

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

它返回一个字符串数组:

{“str1”,“str2”,“str3”}