[英]How to read a whole section from appsettings.json in ASP.NET Core 3.1?
I want to get a whole section from appsettings.json.我想从 appsettings.json 中获取整个部分。
This is my appsettings.json:这是我的 appsettings.json:
{
"AppSettings": {
"LogsPath": "~/Logs",
"SecondPath": "~/SecondLogs"
}
}
C#: C#:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(this.SettingsFilesName);
configuration = builder.Build();
This syntax works fine and returns "~/Logs":此语法工作正常并返回“~/Logs”:
configuration.GetSection("AppSettings:LogsPath");
But how can I have all "AppSettings" section?但是我怎样才能拥有所有“AppSettings”部分呢? Is it possible?
可能吗?
This syntax doesn't work and value property is null.此语法无效,值属性为 null。
configuration.GetSection("AppSettings");
UPDATE :更新:
I have no model and read it in a class. I'm looking for something like this:我没有 model 并在 class 中阅读它。我正在寻找这样的东西:
var all= configuration.GetSection("AppSettings");
and use it like并像使用它
all["LogsPath"] or all["SecondPath"]
they return their values to me.他们把他们的价值观还给我。
That is by design那是设计使然
With和
var configSection = configuration.GetSection("AppSettings");
The configSection
doesn't have a value, only a key and a path. configSection
没有值,只有键和路径。
When GetSection
returns a matching section, Value
isn't populated.当
GetSection
返回匹配部分时,不会填充Value
。 A Key
and Path
are returned when the section exists.该部分存在时返回
Key
和Path
。
If for example you define a model to bind section data to例如,如果您定义一个 model 以将部分数据绑定到
class AppSettings {
public string LogsPath { get; set; }
public string SecondPath{ get; set; }
}
and bind to the section并绑定到该部分
AppSettings settings = configuration.GetSection("AppSettings").Get<AppSettings>();
you would see that the entire section would be extracted and populate the model.您会看到整个部分将被提取并填充 model。
That is because the section will traverse its children and extract their values when populating the model based on matching property names to the keys in the section.这是因为该部分将遍历其子项并在填充 model 时根据匹配的属性名称与该部分中的键提取它们的值。
var configSection = configuration.GetSection("AppSettings");
var children = configSection.GetChildren();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.