Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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");
like image 685
PatrickNolan Avatar asked Jun 19 '17 23:06

PatrickNolan


People also ask

Where is the configuration stored in .NET core?

In ASP.NET Core application, the configuration is stored in name-value pairs and it can be read at runtime from various parts of the application. The name-value pairs may be grouped into multi-level hierarchy.

What is configuration service in .NET core?

The ConfigureServices method is a place where you can register your dependent classes with the built-in IoC container. After registering dependent class, it can be used anywhere in the application. You just need to include it in the parameter of the constructor of a class where you want to use it.

What is AppSettings json in .NET core?

The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.

Where is AppSettings json located?

appsettings. json is one of the several ways, in which we can provide the configuration values to ASP.NET core application. You will find this file in the root folder of our project. We can also create environment-specific files like appsettings.


1 Answers

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.

like image 71
rememberjack Avatar answered Sep 19 '22 05:09

rememberjack