2

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?

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
  • Just FYI...you could use a VS feature(probably VS 2013 onwards) called "Paste as JSON classes" which will generate C# classes from the copied json in your clipboard..this will give you a starting point and you can modify the classes as you may like – Kiran Jul 22 '15 at 19:49
  • @KiranChalla, obviously I don't want to copy paste, I want to keep my code clean and soft-coded. – Shimmy Weitzhandler Jul 22 '15 at 20:17
  • Not sure what you meant, I didn't mean to just use the generated code right away...you can modify it as you may need but keeping in the mind of the deserialization semantics.. – Kiran Jul 22 '15 at 20:23
  • @KiranChalla it has to be done programmatically at runtime, not at design time. – Shimmy Weitzhandler Jul 22 '15 at 20:26

1 Answers1

2

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;
  }
jltrem
  • 12,124
  • 4
  • 40
  • 50
  • Yeah, that's exactly how I ended up, but I prefer my code to be as clean as possible, and the right choice here is array. Did you read [this](https://github.com/aspnet/Announcements/issues/33) announcement? – Shimmy Weitzhandler Jul 22 '15 at 20:23
  • cool. sounds like it will be available in beta5. For now I'm working around the limitation as shown above. – jltrem Jul 22 '15 at 20:26
  • @jitrem, and BTW, since I see you're an AppSettings guru, check out my [other question](http://stackoverflow.com/q/31563575/75500), I'm sure you'll have what to add. – Shimmy Weitzhandler Jul 22 '15 at 20:27