Is there a built in way to serialize array configuration values?

1k Views Asked by At

I'm on a new ASP.NET 5 project.

I'm trying to read an array value, stored in my config.json file, that looks like this:

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

How do I access this from my C# code?

1

There are 1 best solutions below

3
On BEST ANSWER

At least with beta4 arrays aren't supported in config.json. See ASP.NET issue 620. But you could use the following config.json:

"AppSettings": {
  "SiteTitle": "MyProject",
  "Tenants": {
    "ReservedSubdomains": "www, info, admin"
  }
}

and map it to a class like this:

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>(); }
  }
}

This can then be injected into a controller:

public class MyController : Controller
{
  private readonly AppSettings _appSettings;

  public MyController(IOptions<AppSettings> appSettings)
  {
     _appSettings = appSettings.Options;
  }