是否有内置的方法来序列化数组配置值?

时间:2015-07-22 14:42:52

标签: c# visual-studio-2015 asp.net-core-mvc config.json

我正在开发一个新的ASP.NET 5项目。

我试图读取存储在config.json文件中的数组值,如下所示:

{
  "AppSettings": {
    "SiteTitle": "MyProject",
    "Tenants": {
      "ReservedSubdomains": ["www", "info", "admin"]
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-MyProject....."
    }
  }
}

如何从我的C#代码中访问它?

1 个答案:

答案 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;
  }