是否有内置的方法来序列化数组配置值?
Is there a built in way to serialize array configuration values?
我正在进行一个新的 ASP.NET 5 项目。
我正在尝试读取存储在我的 config.json
文件中的数组值,它看起来像这样:
{
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": ["www", "info", "admin"]
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\mssqllocaldb;Database=aspnet5-MyProject....."
}
}
}
如何从我的 C# 代码访问它?
至少 config.json
不支持 beta4 数组。参见 ASP.NET issue 620。但是你可以使用下面的 config.json
:
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": "www, info, admin"
}
}
并将其映射到 class,如下所示:
public class AppSettings
{
public string SiteTitle { get; set; }
public AppSettingsTenants Tenants { get; set; } = new AppSettingsTenants();
}
public class AppSettingsTenants
{
public string ReservedSubdomains { get; set; }
public List<string> ReservedSubdomainList
{
get { return !string.IsNullOrEmpty(ReservedSubdomains) ? ReservedSubdomains.Split(',').ToList() : new List<string>(); }
}
}
然后可以将其注入控制器:
public class MyController : Controller
{
private readonly AppSettings _appSettings;
public MyController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Options;
}
我正在进行一个新的 ASP.NET 5 项目。
我正在尝试读取存储在我的 config.json
文件中的数组值,它看起来像这样:
{
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": ["www", "info", "admin"]
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\mssqllocaldb;Database=aspnet5-MyProject....."
}
}
}
如何从我的 C# 代码访问它?
至少 config.json
不支持 beta4 数组。参见 ASP.NET issue 620。但是你可以使用下面的 config.json
:
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": "www, info, admin"
}
}
并将其映射到 class,如下所示:
public class AppSettings
{
public string SiteTitle { get; set; }
public AppSettingsTenants Tenants { get; set; } = new AppSettingsTenants();
}
public class AppSettingsTenants
{
public string ReservedSubdomains { get; set; }
public List<string> ReservedSubdomainList
{
get { return !string.IsNullOrEmpty(ReservedSubdomains) ? ReservedSubdomains.Split(',').ToList() : new List<string>(); }
}
}
然后可以将其注入控制器:
public class MyController : Controller
{
private readonly AppSettings _appSettings;
public MyController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Options;
}