.netconfigurationmanager

Is there a way to get whole section group in .Net 6.0 Configuration using IConfiguration interface


Is there a way to access the whole section Group in .Net 6.0 Configuration from custom json file?

There's a custom json injected into configuration on startup using AddJsonFile() method.

When attempting to get the values of the file, it is possible to access only one single value with GetSection("Foo:Bar") using IConfiguration.

Is there a way to get the list of objects by using only group key or whole Json file's content as a string?

Json file's content:

{
  "Versions": {
    "fullVersion": "1.0.0.0",
    "clientVersion": "2022.01.10",
    "apiVersion": "2022.05.09"
  }
}

Controller:

    private IConfiguration _configuration;

    public VersionController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public Version GetAllVersionsFromJson()
    {
       // Not getting the content here
       var versionsList = _configuration.GetSection("Versions");
       // Getting only one object out of 3
       var singleVersion = _configuration.GetSection("Versions:fullVersion");

       /*More logic*/

    }           
  

Version class:

public class Version
{        
    public string Label { get; set; }
    
    public string BuildNumber { get; set; }   
}

Solution

  • I managed to get the data and fill in Version class, but I consider this not to be an ideal solution.

    I've changed name of the section in json and added new helper model to be an exact match for the json's data:

    public class VersionConfigurations
    {
        public string fullVersion { get; set; }
        public string clientVersion { get; set; }
        public string apiVersion { get; set; }
    }
    

    After that the data was neatly matched in the controller:

       var configVerions = _configuration.GetSection("VersionConfigurations").Get<VersionConfigurations>();
    

    Then the part I am not too happy about: reading names of properties and their values and getting the versions into version list:

        foreach (var configVer in configVerions.GetType().GetProperties())
        {
            versionsList.Add(new Version()
            {
                Label = configVer.Name,
                BuildNumber = (string)configVer.GetValue(configVerions)
            });
        };