Search code examples
c#asp.net-core.net-coreapp-config

How to check if config section exists?


I'm trying to implement a simple config service to my dotnet core projects.

I want to return null if requested config section is not present in any of the config files added.

My current code to retrieve a config section:

private static IConfigurationRoot _configuration { get; set; }
private static IConfigurationBuilder _builder;

public JsonConfigService()
{
   _builder = new ConfigurationBuilder();

}

public T GetConfigModel<T>(string name) where T : new()
{
    if (string.IsNullOrWhiteSpace(name))
        return default(T);

    var section = _configuration.GetSection(name);

    if (section == null || string.IsNullOrWhiteSpace(section.Value))
        return default(T);

    var value = new T();
    section.Bind(value);

    return value;
} 

public void RegisterSource(string source)
{
    _builder.AddJsonFile(source);
    _configuration = _builder.Build();
}

the problem is:

  • Section is never null whenever the requested config section is available in the config or not.
  • section.Value is always null (only tested against complex types)

How do i find out if config section "NotHere" is actually in the json file or not before binding?


Solution

  • Using GetValue method instead of GetSection returns null if the section is not existing in the config.

    Usage:

    public T GetConfigModel<T>(string name) where T : new()
    {
        if (string.IsNullOrWhiteSpace(name))
            return default(T);
    
        try
        {
            return _configuration.GetValue<T>(name);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }