简体   繁体   中英

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.

This is my appsettings.json:

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

C#:

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

This syntax works fine and returns "~/Logs":

configuration.GetSection("AppSettings:LogsPath");

But how can I have all "AppSettings" section? Is it possible?

This syntax doesn't work and value property is null.

 configuration.GetSection("AppSettings");

UPDATE :

I have no model and read it in a class. I'm looking for something like this:

 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.

When GetSection returns a matching section, Value isn't populated. A Key and Path are returned when the section exists.

If for example you define a model to bind section data to

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.

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.

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

var children = configSection.GetChildren();

Reference Configuration in ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM