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

35

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

即使该部分不存在,以下代码仍将返回一个已实例化的实例。

例如:

var section = this.Configuration.GetSection<TestSection>("testsection");

这就是我正在使用的。在我的示例中,this.Configuration 是一个具有 GetSection 方法的 IConfigurationRoot。有人有什么建议吗? - PatrickNolan
4个回答

59

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

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

由于GetSection(sectionKey)永远不会返回null, 所以你可以安全地在其返回值上调用Exists

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


16
Query Configuration的子节点,检查是否存在名称为"testsection"的节点。
var sectionExists = Configuration.GetChildren().Any(item => item.Key == "testsection"));

如果"testsection"存在,应该返回true,否则返回false。


你在使用哪个库来进行“配置”? - superninja
2
ASP.NET Core已经在包Microsoft.Extensions.Configuration中内置了对多个配置提供程序的支持。请参阅ASP.NET Core中的配置 - Pradeep Kumar

15
.Net 6中,有一个新的扩展方法:ConfigurationExtensions.GetRequiredSection()。如果没有给定key的部分,则会抛出InvalidOperationException
此外,如果您正在使用带有AddOptions<TOptions>()IOptions模式,则还在.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();

2
你用这个救了我的命,非常感谢你! - Thomas

0
你还可以使用 DataAnnotations
builder.Services.AddOptions<AppSettings>()
    .BindConfiguration(nameof(AppSettings))
    .ValidateDataAnnotations()//
    .ValidateOnStart();

这样做可以确保数据注释起作用。
using System.ComponentModel.DataAnnotations;

public class AppSettings()
{
    [Required]
    public required string MyProperty { get; set; }
}

只有在设置了AppSettingsMyProperty的情况下才能正常工作。
"AppSettings":{
    "MyProperty ":"non-empty string"
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接