我想从 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
不会被填充。当该部分存在时,返回一个 Key
和 Path
。
例如,如果您定义一个模型来将部分数据绑定(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();
关于c# - 如何从 ASP.NET Core 3.1 中的 appsettings.json 读取整个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353390/