'How to check if Configuration Section exists in .NET Core?

How can you check if a configuration section exists in the appsettings.json in .NET Core?

Even if a section doesn't exist, the following code will always return an instantiated instance.

e.g.

var section = this.Configuration.GetSection<TestSection>("testsection");


Solution 1:[1]

Since .NET Core 2.0, you can also call the ConfigurationExtensions.Exists extension method to check if a section exists.

var section = this.Configuration.GetSection("testsection");
var sectionExists = section.Exists();

Since GetSection(sectionKey) never returns null, you can safely call Exists on its return value.

It is also helpful to read this documentation on Configuration in ASP.NET Core.

Solution 2:[2]

In .Net 6, there is a new extension method for this:

ConfigurationExtensions.GetRequiredSection()

Throws InvalidOperationException if there is no section with the given key.


Further, if you're using the IOptions pattern with AddOptions<TOptions>(), the ValidateOnStart() extension method was also added in .Net 6 to be able to specify that validations should run at startup, instead of only running when the IOptions instance is resolved.

With some questionable cleverness you can combine it with GetRequiredSection() to make sure a section actually exist:

// Bind MyOptions, and ensure the section is actually defined.
services.AddOptions<MyOptions>()
    .BindConfiguration(nameof(MyOptions))
    .Validate<IConfiguration>((_, configuration)
        => configuration.GetRequiredSection(nameof(MyOptions)) is not null)
    .ValidateOnStart();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rememberjack
Solution 2