在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:
"MySetting": {
"MyValues": [
"C#",
"ASP.NET",
"SQL"
]
},
我的设置类:
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;
}
}
访问值:
var myValues = this._mySetting.MyValues;
从appsettings.json中获取所有section的所有值
public static string[] Sections = { "LogDirectory", "Application", "Email" };
Dictionary<string, string> sectionDictionary = new Dictionary<string, string>();
List<string> sectionNames = new List<string>(Sections);
sectionNames.ForEach(section =>
{
List<KeyValuePair<string, string>> sectionValues = configuration.GetSection(section)
.AsEnumerable()
.Where(p => p.Value != null)
.ToList();
foreach (var subSection in sectionValues)
{
sectionDictionary.Add(subSection.Key, subSection.Value);
}
});
return sectionDictionary;