如何检查MVC Core配置文件中是否存在某个部分?

问题描述:

如何检查已加载的ASP.NET Core配置文件中的特定部分?

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

我有一个JSON配置文件,可以通过 ConfigurationBuilder.AddJsonFile 方法将其加载到 Startup 类中.

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

此JSON文件是具有以下布局的数组:

This JSON file is an array with this layout:

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

但是其中一些没有 Keys .我尝试针对 null 检查 section.GetSection("Keys")的返回类型,但是即使部分不存在.

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.

使用 GetChildren 方法:

var keysExists = Configuration.GetChildren().Any(x => x.Key == "Keys"));