Search code examples
.net-5configuration-files

Load section of config file into dictionary in net 5.0


I have to work on an application in net 5.0 not developed by me, that I don't know.

I would like to add a section in the config file and load it into a dictionary.

this is the section in config file:

{
  "MyApp": {
    "ServiceExceptions": [
        { "Key1": "Value1" },
        { "Key2": "Value2" }
    ]
  }
}

this code load the configuration:

public static IConfiguration GetConfiguration(string name)
{
    IConfiguration oConfiguration = null;
    string basePath = Path.GetDirectoryName(typeof(SharedHelper).Assembly.Location);
    string configPath = Path.Combine(basePath, "Config");

    string fileConfig = string.Format("{0}.{1}.json", name, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));

    oConfiguration = new ConfigurationBuilder()
                           .SetBasePath(configPath)
                           .AddJsonFile(fileConfig, optional: false, reloadOnChange: true)
                           .Build();
        return oConfiguration;
    }

this is the code to load to bind the dictionary, but myExceptions is null:

_Configuration = GetConfiguration("BD.Authentication.DWA");
Dictionary<string, string> myExceptions = null;
_Configuration.GetSection("MyApp:ServiceExceptions").Bind(myExceptions);
Debug.WriteLine(myExceptions.Count); // throws exception null reference

somewhere are loaded the data, but i dont know how to pull outenter image description here


Solution

  • Just move the config file in:

    {
      "MyApp": {
        "ServiceExceptions": 
            { "Key1": "Value1" },
            { "Key2": "Value2" }
      }
    }
    

    and retrive the values:

    var serviceTypeExceptions = _Configuration.GetSection("MyApp:ServiceExceptions").Get<Dictionary<string, string>>();