我正在开发一个新的ASP.NET 5项目。
我试图读取存储在config.json
文件中的数组值,如下所示:
{
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": ["www", "info", "admin"]
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-MyProject....."
}
}
}
如何从我的C#代码中访问它?
答案 0 :(得分:2)
至少在config.json
中不支持beta4阵列。见ASP.NET issue 620。但您可以使用以下config.json
:
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": "www, info, admin"
}
}
并将其映射到这样的类:
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;
}