首页 > 解决方案 > 如何从 ASP.NET Core 3.1 中的 appsettings.json 读取整个部分?

问题描述

我想从 appsettings.json 中获取整个部分。

这是我的 appsettings.json:

{
 "AppSettings": {
  "LogsPath": "~/Logs",
  "SecondPath": "~/SecondLogs"
  } 
}

C#:

var builder = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile(this.SettingsFilesName);
        configuration = builder.Build();

此语法工作正常并返回 "~/Logs" :

configuration.GetSection("AppSettings:LogsPath");

但是我怎样才能拥有所有“AppSettings”部分?可能吗?

此语法不起作用,并且 value 属性为空。

 configuration.GetSection("AppSettings");

更新

我没有模型,在课堂上阅读。我正在寻找这样的东西:

 var all= configuration.GetSection("AppSettings");

并像使用它一样

all["LogsPath"] or  all["SecondPath"]

他们把他们的价值观还给我。

标签: c#asp.net-core.net-coreappsettings

解决方案


这是设计使然

var configSection = configuration.GetSection("AppSettings");

configSection没有值,只有键和路径。

GetSection返回匹配部分时,Value不填充。当节存在时返回AKey和。Path

例如,如果您定义一个模型来将部分数据绑定到

class AppSettings {
    public string LogsPath { get; set; }
    public string SecondPath{ get; set; }
}

并绑定到该部分

AppSettings settings = configuration.GetSection("AppSettings").Get<AppSettings>();

您会看到整个部分将被提取并填充模型。

这是因为在填充模型时,该部分将遍历其子项并提取其值,该模型基于与该部分中的键匹配的属性名称。

var configSection = configuration.GetSection("AppSettings");

var children = configSection.GetChildren();

ASP.NET Core 中的参考配置


推荐阅读