c# - 如何从 ASP.NET Core 3.1 中的 appsettings.json 读取整个部分?

标签 c# asp.net-core .net-core appsettings

我想从 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 属性为 null。

 configuration.GetSection("AppSettings");

更新:

我没有模型,在类里面看的。我正在寻找这样的东西:

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

并像使用它一样

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

他们将他们的值(value)返回给我。

最佳答案

这是设计使然

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

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

GetSection 返回匹配部分时,Value 不会被填充。当该部分存在时,返回一个 KeyPath

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

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

并绑定(bind)到该部分

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

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

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

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

var children = configSection.GetChildren();

引用 Configuration in ASP.NET Core

关于c# - 如何从 ASP.NET Core 3.1 中的 appsettings.json 读取整个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353390/

相关文章:

asp.net-core - 如何在 VS 2017 中更新 Microsoft.NETCore.App SDK 版本

c# - 从 ViewModel 构造函数发送时未收到 MVVM Light 消息

c# - 使用复杂的 XML 数据将 XML 转换为 JSON

c# - 我应该手动编码 ADO.Net 数据库访问吗?

c# - 如何解决服务层内部的循环依赖

entity-framework - 在 EF Core 2.0 中使用 OwnsOne 方法映射属性

c# - 如何使用 EF Core 在 .NET core 3.1(不带 LINQ)中创建用于 CRUD 操作的自定义扩展方法?

c# - 数据绑定(bind)到文本框不起作用

c# - Web Essentials 浏览器链接在 asp mvc 6 项目中不起作用

asp.net-core - 从文件系统托管时,docfx 菜单缺少 "Articles"、 "Api Documentation"但显示在 localhost :8080