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

送分小仙女□ 提交于 2020-05-28 14:00:50

问题


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");

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/44641488/how-to-check-if-configuration-section-exists-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!