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");
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With