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

PatrickNolan picture PatrickNolan · Jun 20, 2017 · Viewed 10.1k times · Source

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");

Answer

rememberjack picture rememberjack · Jan 13, 2019

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.