I am trying to retrieve an IConfiguration section from my appsettings.json
file which is an array of strongly typed elements and i keep getting an empty collection.
I am using whatever Asp .Net Core 3.1
uses by default when deserializing the IConfiguration
section:
(I am using JsonSerializer
for all json specific tasks )
DTO
public class Element
{
[JsonPropertyName("key")]
public string Key {get;set;}
[JsonPropertyName("value")]
public string Value{get;set;}
}
public class Elements
{
[JsonPropertyName("fields")]
public IEnumerable<Element>Fields{get;set;}
}
public class Config
{
[JsonPropertyName("elements")]
public Elements Elements{get;set;}
}
appsettings.json
{
"config":{
"fields":[
{"key":"a","value":"aa"},
{"key":"b","value":"bb"},
{"key":"c","value":"cc"}
}
}
Startup
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) {
this.Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) {
Config config=this.Configuration.GetSection("config").Get<Config>(); // elements count is 0
Elements elements = this.Configuration.GetSection("config:elements").Get<Elements>(); // elements count is 0
}
}
I have tried :
- Changing my
IEnumerable
of typed elements (Elements
) toArray
,List
,IList
to no avail - Placing my
Elements
field directly in the root to no avail
P.S
If i change from [SomeCollection]<Element>
to [SomeCollection]<string>
it sees all the elements , so there is obviously a problem when deserializing collections of types.