Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 535
Joshua Barron Avatar asked Aug 10 '15 21:08

Joshua Barron


2 Answers

I have solved a similar problem where I wanted to bind the entire IConfigurationRoot or IConfigurationSection to a Dictionary. Here is an extension class:

public class ConfigurationExtensions
{
    public static Dictionary<string, string> ToDictionary(this IConfiguration config, bool stripSectionPath = true)
    {
        var data = new Dictionary<string, string>();
        var section = stripSectionPath ? config as IConfigurationSection : null;
        ConvertToDictionary(config, data, section);
        return data;
    }

    static void ConvertToDictionary(IConfiguration config, Dictionary<string, string> data = null, IConfigurationSection top = null)
    {
        if (data == null) data = new Dictionary<string, string>();
        var children = config.GetChildren();
        foreach (var child in children)
        {
            if (child.Value == null)
            {
                ConvertToDictionary(config.GetSection(child.Key), data);
                continue;
            }

            var key = top != null ? child.Path.Substring(top.Path.Length + 1) : child.Path;
            data[key] = child.Value;
        }
    }
}

And using the extension:

IConfigurationRoot config;
var data = config.ToDictionary();
var data = config.GetSection("CustomSection").ToDictionary();

There is an optional parameter (stripSectionPath) to either retain the full section key path or to strip the section path out, leaving a relative path.

var data = config.GetSection("CustomSection").ToDictionary(false);
like image 151
Michal Steyn Avatar answered Oct 04 '22 00:10

Michal Steyn


configuration.Get is for getting a value to get a section you need

IConfiguration mysection = configuration.GetConfigurationSection("SectionKey");
like image 33
Joe Audette Avatar answered Oct 04 '22 00:10

Joe Audette