I'm trying to bind to a custom configuration object which should be populated by an appsettings.json file.
My appsettings looks a bit like:
{
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Settings": {
"Foo": {
"Interval": 30,
"Count": 10
}
}
}
The settings classes look like:
public class Settings
{
public Foo myFoo {get;set;}
}
public class Foo
{
public int Interval {get;set;}
public int Count {get;set;}
public Foo()
{}
// This is used for unit testing. Should be irrelevant to this question, but included here for completeness' sake.
public Foo(int interval, int count)
{
this.Interval = interval;
this.Count = count;
}
}
When I try to bind the Configuration to an object the lowest level it works:
Foo myFoo = Configuration.GetSection("Settings:Foo").Get<Foo>();
myFoo
correctly has an Interval
and a Count
with values set to 30 and 10 respectively.
But this doesn't:
Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();
mySettings
has a null foo
.
Frustratingly, if I use the debugger I can see that the necessary data is being read in from the appsettings.json file. I can step down into Configuration => Non-Public Members => _providers => [0] => Data
and see all of the information I need. It just won't bind for a complex object.
Can I add more than two appsettings. json files in dotnet core? Of course, we can add and use multiple appsettings. json files in ASP.NET Core project.
The IConfiguration is an interface for . Net Core 2.0. The IConfiguration interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IConfiguration interface is used to read Settings and Connection Strings from AppSettings. json file.
Your property must match the property names in "appsettings.json".
You must rename your Settings' myFoo
property into Foo
, because that's property name in the json file.
You can also use the JsonProperty(Included in Newtonsoft.Json) Annotation to tell the serializer what to do like below.
public class Settings
{
[JsonProperty("Foo")]
public Foo myFoo {get;set;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With