在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"));
    }
}

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


当前回答

设置。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/"

其他回答

public class MyArray : List<string> { }

services.Configure<ShipmentDetailsDisplayGidRoles>(Configuration.GetSection("MyArray"));

public SomeController(IOptions<MyArray> myArrayOptions)
{
    myArray = myArrayOptions.Value;
}

灯塔3.1

Json配置:

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

然后创建一个User.cs类,它具有与上面Json配置中的User对象对应的auto属性。然后你可以引用Microsoft.Extensions.Configuration.Abstractions并执行以下操作:

List<User> myTestUsers = Config.GetSection("TestUsers").GetSection("User").Get<List<User>>();

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

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

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

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

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

.Net Core 7.x中处理对象的不同方法

在appsettings.json:

{
      "People": [
          { "FirstName": "Glen", "LastName": "Johnson", "Age": 30 },
          { "FirstName": "Matt", "LastName": "Smith", "Age": 40 },
          { "FirstName": "Fred", "LastName": "Williams", "Age": 50 }
      ]
}

Person类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

在代码中:

var appConfig = App.Current.AppConfiguration;   // Or could be passed in through DI
var children = appConfig.GetSection("People")
    .GetChildren()
    .ToList();

var people = new List<Person>();
foreach (var child in children)
{
    var rec = new Person
    {
        FirstName = appConfig[$"{child.Path}:FirstName"],
        LastName = appConfig[$"{child.Path}:LastName"],
        Age = int.Parse(appConfig[$"{child.Path}:Age"]),
    };
    people.Add(rec);
}

在IOptions不起作用后,我发现这更简单,序列化时要做的事情也少得多。

//appsettings.json
"DatabaseModelCreationOptions": {
    "Users": [
      {
        "Id": "1",
        "UserName": "adminuser",
        "Email": "youremail@myemail.com",
        "Password": "!Ch4",
        "Player": "Admin",
        "PlayerInitials": "ADMIN",
        "ApiKey": "40753ey"
      }
    ],   
    "UserRoles": [
      {
        "Id": "af9986df",
        "Name": "Admin",
        "ConcurrencyStamp": "ddd53170"
      },
      {
        "Id": "03b82b0e",
        "Name": "Manager",
        "ConcurrencyStamp": "65da3f89"
      }
    ]
}

我需要的类,我不需要给你们看嵌套的类属性,你们可以在上面看到。

public class DatabaseModelCreationOptions
{
    public IEnumerable<User>? Users { get; set; }
    public IEnumerable<UserRole>? UserRoles { get; set; }
}

然后调用GetSection("")。得到

var dbOptions = configuration.GetSection("DatabaseModelCreationOptions")
    .Get<DatabaseModelCreationOptions>();