Joshua Barron Joshua Barron - 3 months ago 8
ASP.NET (C#) Question

Retrieve sections from config.json in ASP.NET 5

Let's say I have a

config.json
like this:

{
"CustomSection": {
"A": 1,
"B": 2
}
}


I know I can use an
IConfiguration
object to get specific settings, i.e.,
configuration.Get("CustomSection:A")
, but can I grab the whole hierarchy (in any type - even a raw string would be fine)? When I try
configuration.Get("CustomSection")
, I get a
null
result, so I think this isn't supported by default.

My use case is grabbing entire configuration dictionaries at once without having to grab each individual setting - some properties may not be known at compile time.

Answer

Edit: updating this answer for the 1.0 release of Core.

This is possible now if you use a strongly typed object, for example:

public class CustomSection 
{
   public int A {get;set;}
   public int B {get;set;}
}

//In Startup.cs
services.Configure<CustomSection>(Configuration.GetSection("CustomSection"));
//You can then inject an IOptions instance
public HomeController(IOptions<CustomSection> options) 
{
    var settings = options.Value;
}
Comments