Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a section in MVC Core configuration file exist?

How can I check if a specific section in loaded ASP.NET Core configuration file exist?

I have a JSON configuration file that I load it in Startup class via ConfigurationBuilder.AddJsonFile method.

This JSON file is an array with this layout:

{
   "Url": "",
   "Regex": [ "", "" ],
   "Keys": {
     "Title": "",
     "Description": "",
     "Keywords": [ "" ]
   }
}

But some of them doesn't have Keys. I tried to check return type of section.GetSection("Keys") against null, But it doesn't return null even if Keys section isn't present.

like image 923
MRB Avatar asked Jan 12 '17 06:01

MRB


People also ask

Which file contains configuration details in ASP.NET Core?

web. config file is an XML-based configuration file used in ASP. NET-based applications to manage various settings that are concerned with the configuration of our website. In this way, we can separate our application logic from configuration logic.

How read config file in ASP.NET Core?

To read configuration values in ASP.NET Core, you need to follow the Options pattern. To implement it, define a configuration class matching the values you want to read from the appsetttings. json file and use the default dependency container to inject the read values.

What is the configuration file for ASP NET MVC core app?

ASP.NET MVC configuration In ASP.NET apps, configuration uses the built-in . NET configuration files, web. config in the app folder and machine. config on the server.

Where is the configuration stored in .NET Core?

Configuration In ASP.NET Core. ASP.NET Core supports many methods of configuration. 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.


1 Answers

Also it is possible to use use Exists extension method from Microsoft.Extensions.Configuration.Abstractions. Exapmle:

var section = Configuration.GetSection("Keys")
var sectionExists = section.Exists();

or

public bool IsExistsConfigurationSection(string sectionKey)
{
    return Configuration.GetSection(sectionKey).Exists();
}
like image 153
Алексей Сидоров Avatar answered Sep 28 '22 08:09

Алексей Сидоров