c# - 如何从 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"]
他们把他们的价值观还给我。
解决方案
这是设计使然
和
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 中的参考配置
推荐阅读
- java - 在更改数组的值时遇到非法的表达式开始错误
- string - golang:关于字符串连接的具体问题
- python - 如何使用 Selenium 从 LinkedIn 公司页面中抓取员工人数?
- r - 为交互式闪亮小部件参数制作反应变量
- ios - 回调在没有初始化程序的类中无法正常工作?
- java - Spring Boot banner.gif 没有动画
- c++ - consteval 是否允许在函数参数上使用 static_assert?
- python - 在 pytest-ing 时禁用每个测试“点”
- ruby-on-rails - Ruby on Rails:干模式干验证不验证存在
- memgraphdb - 无法为 memgraphdb 安装 pymgclient