在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"));
}
}
上面是我的代码。结果是零。
如何获取数组?
最近我还需要从appsettings中读取一个简单的字符串数组。Json文件(以及其他类似的. Json配置文件)。
对于我的方法,我创建了一个简单的扩展方法:
public static class IConfigurationRootExtensions
{
public static string[] GetArray(this IConfigurationRoot configuration, string key)
{
var collection = new List<string>();
var children = configuration.GetSection(key)?.GetChildren();
if (children != null)
{
foreach (var child in children) collection.Add(child.Value);
}
return collection.ToArray();
}
}
原始海报的.json文件如下所示:
{
"MyArray": [
"str1",
"str2",
"str3"
]
}
使用上面的扩展方法,它使读取这个数组成为一个非常简单的一行事务,如下面的例子所示:
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
string[] values = configuration.GetArray("MyArray");
在运行时,在值上设置一个'QuickWatch'的断点,以验证我们已经成功地将.json配置文件中的值读入一个字符串数组:
这为我工作,从我的配置返回一个字符串数组:
var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
.Get<string[]>();
我的配置部分是这样的:
"AppSettings": {
"CORS-Settings": {
"Allow-Origins": [ "http://localhost:8000" ],
"Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
}
}
设置。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/"
在应用程序设置中添加一个级别。json:
{
"MySettings": {
"MyArray": [
"str1",
"str2",
"str3"
]
}
}
创建一个代表你的section的类:
public class MySettings
{
public List<string> MyArray {get; set;}
}
在你的应用启动类中,绑定你的模型并将其注入到DI服务中:
services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
在你的控制器中,从DI服务中获取配置数据:
public class HomeController : Controller
{
private readonly List<string> _myArray;
public HomeController(IOptions<MySettings> mySettings)
{
_myArray = mySettings.Value.MyArray;
}
public IActionResult Index()
{
return Json(_myArray);
}
}
你也可以把你的整个配置模型存储在控制器的属性中,如果你需要所有的数据:
public class HomeController : Controller
{
private readonly MySettings _mySettings;
public HomeController(IOptions<MySettings> mySettings)
{
_mySettings = mySettings.Value;
}
public IActionResult Index()
{
return Json(_mySettings.MyArray);
}
}
ASP。NET Core的依赖注入服务就像一个魔法一样:)