如何检查.NET Core中是否存在配置节?

Pat*_*lan 5 .net json app-config appsettings asp.net-core

如何检查appsettings.json.NET Core中是否存在配置节?

即使一个节不存在,以下代码也将始终返回实例化的实例。

例如

var section = this.Configuration.GetSection<TestSection>("testsection");
Run Code Online (Sandbox Code Playgroud)

小智 16

从.NET Core 2.0开始,您还可以调用ConfigurationExtensions.Exists扩展方法来检查是否存在某个节。

var section = this.Configuration.GetSection("testsection");
var sectionExists = section.Exists();
Run Code Online (Sandbox Code Playgroud)

由于GetSection(sectionKey) 从不返回null,因此可以安全地调用Exists其返回值。

阅读有关ASP.NET Core中的配置的文档也很有帮助。


MrV*_*ype 15

.Net 6中,有一个新的扩展方法:

ConfigurationExtensions.GetRequiredSection()

InvalidOperationException如果没有包含给定键的部分,则抛出此异常。


此外,如果您使用IOptionswith 模式AddOptions<TOptions>(), .Net 6 中还添加了ValidateOnStart()扩展方法,以便能够指定验证应在启动时运行,而不是仅在IOptions解析实例时运行。

通过一些值得怀疑的聪明才智,您可以将其结合起来GetRequiredSection()以确保某个部分确实存在:

// Bind MyOptions, and ensure the section is actually defined.
services.AddOptions<MyOptions>()
    .BindConfiguration(nameof(MyOptions))
    .Validate<IConfiguration>((_, configuration)
        => configuration.GetRequiredSection(nameof(MyOptions)) is not null)
    .ValidateOnStart();
Run Code Online (Sandbox Code Playgroud)

  • 你用这个救了我的命,非常感谢你! (2认同)

Pra*_*mar 12

查询 Configuration 的子项并检查是否有名称为“testsection”的子项

var sectionExists = Configuration.GetChildren().Any(item => item.Key == "testsection"));
Run Code Online (Sandbox Code Playgroud)

如果“testsection”存在,这应该返回true,否则返回false。

  • ASP.NET 核心已经对包“Microsoft.Extensions.Configuration”中的多个配置提供程序提供了内置支持。请参阅[ASP.NET Core 中的配置](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1)。 (2认同)