Really struggling with this one - is it supposed to be this hard?!
I have a simple object array in my appsettings:
"AppSettings": {
"Names": [
{
"Id": "1",
"Name": "Mike"
},
{
"Id": "2",
"Name": "John"
}
]
}
I then have a class
public class AppSettings
{
public List<Names> Names { get; set; } = new List<Names>();
}
public class Names
{
public string Id { get; set; }
public string Name { get; set; }
}
I read in my app settings:
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json").Build();
var config = new AppSettings();
This is where stuff goes wrong:
config.Names = configuration.GetSection("AppSettings:Names") //<<<< what do I do here?
It seems like it's all tied to IConfigurationSection
which is not helpful.
Get the entire object graph from the setting using the ConfigurationBinder.Get<T>
extension.
ConfigurationBinder.Get<T>
binds and returns the specified type.ConfigurationBinder.Get<T>
may be more convenient than usingConfigurationBinder.Bind
. The following code shows how to useConfigurationBinder.Get<T>
with theAppSettings
class:
//...
AppSettings config = configuration.GetSection("AppSettings").Get<AppSettings>();
//...
Reference Configuration in ASP.NET Core