34

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");
Yannic Hamann
  • 4,655
  • 32
  • 50
PatrickNolan
  • 1,671
  • 2
  • 20
  • 40
  • That's what I'm using. In my example this.Configuration is IConfigurationRoot which has a GetSection method. Does anyone have any suggestions? – PatrickNolan Jun 21 '17 at 02:29

3 Answers3

58

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.

rememberjack
  • 751
  • 1
  • 7
  • 8
15

Query the children of Configuration and check if there is any with the name "testsection"

var sectionExists = Configuration.GetChildren().Any(item => item.Key == "testsection"));

This should return true if "testsection" exists, otherwise false.

Pradeep Kumar
  • 1,281
  • 7
  • 9
  • which library are you using for the `configuration`? – superninja Aug 22 '18 at 18:00
  • 2
    ASP.NET core already has an inbuilt support for several configuration providers in the package `Microsoft.Extensions.Configuration`. Refer to [Configuration in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1). – Pradeep Kumar Aug 27 '18 at 03:12
13

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();
Leaky
  • 3,088
  • 2
  • 26
  • 35