在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/"
这是一个老问题了,但是我可以给出一个用c# 7标准更新的。net Core 2.1的答案。假设我只在appsettings.Development.json中有一个列表,例如:
"TestUsers": [
{
"UserName": "TestUser",
"Email": "Test@place.com",
"Password": "P@ssw0rd!"
},
{
"UserName": "TestUser2",
"Email": "Test2@place.com",
"Password": "P@ssw0rd!"
}
]
我可以在Microsoft.Extensions.Configuration.IConfiguration被实现并像这样连接的任何地方提取它们:
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)>();
现在我有了一个良好类型对象的列表。如果我点击testUsers.First(), Visual Studio现在应该会显示“用户名”、“电子邮件”和“密码”选项。