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

4

40

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");
Pod answered 19/6, 2017 at 23:34 Comment(1)
That's what I'm using. In my example this.Configuration is IConfigurationRoot which has a GetSection method. Does anyone have any suggestions?Pod
N
16

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.

Natividad answered 24/6, 2017 at 6:13 Comment(2)
which library are you using for the configuration?Charlot
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.Natividad
L
66

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.

Loisloise answered 13/1, 2019 at 1:51 Comment(0)
N
16

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.

Natividad answered 24/6, 2017 at 6:13 Comment(2)
which library are you using for the configuration?Charlot
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.Natividad
D
16

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();
Diaz answered 2/2, 2022 at 2:29 Comment(2)
You saved my life with this one, thank you so much!President
I dont't think it would be a best practice. Relying on exceptions to check conditions, that can be checked otherwise (in this case via the ConfigurationExtensions.Exists extension method) makes your code to perform slower. learn.microsoft.com/en-us/dotnet/standard/exceptions/…Suspension
A
2

You can also use DataAnnotations

builder.Services.AddOptions<AppSettings>()
    .BindConfiguration(nameof(AppSettings))
    .ValidateDataAnnotations()//👈
    .ValidateOnStart();

That will make sure the data annotations works:

using System.ComponentModel.DataAnnotations;

public class AppSettings()
{
    [Required]
    public required string MyProperty { get; set; }
}

Will only work if AppSettings and MyProperty are set:

"AppSettings":{
    "MyProperty ":"non-empty string"
  }
Abrupt answered 28/10, 2023 at 13:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.