Iterate through and read all appsettings keys in asp.net core

Viewed 3979

I have got some configuration added in my appsettings.json file of my asp.net core 3.0 web api project and the file looks something like this:

{
  "Logging":{..},
  "AllowedHosts": "*",
  "Section1": {
     "Key1": "Value1",
     "Key2": "Value2",
     ....
  }
}

I want to iterate through all the keys in this particular section, Section1 and perform some action on them. I tried the following but it doesn't work:

foreach (var key in ConfigurationManager.AppSettings.AllKeys)
                {
                    var key = ConfigurationManager.AppSettings["Key1"];
                    // perform some action
                }

ConfigurationManager.AppSettings doesn't contain anything as can be seen in the screenshot below: enter image description here

What else do I need to do to make this work?

I have tried var v = this._configuration.GetSection("Section1").GetSection("Key1");where _configuration is of the type IConfiguration and it works as expected. But again, like I mentioned I don't want this, instead I want to iterate through all the list of keys in the appsettings and perform some action on them.

Any help would be great.

2 Answers

Something like this will let you iterate over the keys and values within the appsettings file specifically.

public static void DoSomethingWithConfigurationManager(IConfiguration config)
{
    var root = config as ConfigurationRoot;
    if (root != null)
    {
        var appSettingsProvider = root.Providers.FirstOrDefault(x => x is JsonConfigurationProvider && ((JsonConfigurationProvider)x).Source?.Path == "appsettings.json") as JsonConfigurationProvider;
        if (appSettingsProvider != null)
        {
            var dataElement = appSettingsProvider.GetType().GetProperty("Data", BindingFlags.Instance | BindingFlags.NonPublic);
            var dataValue = (SortedDictionary<string, string>)dataElement.GetValue(appSettingsProvider);
            foreach (var item in dataValue)
            {
                //Do something with item.Key and item.Value
            }
        }
    }

I have used like this in my program.cs file and it pick up the value correctly with appsettings.json file you can also try like this.

Program.cs

IHost host = new HostBuilder()            
                 .ConfigureAppConfiguration((hostContext, configApp) =>
                 {
                     configApp.AddJsonFile($"appsettings.json", true);
                     configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
}

appsettings.json

{
  "https_port": 443,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
Related