Reputation: 51
I looked through various solutions posted on StackOverflow -- many were outdated. The intent is to use IConfigurationSection.Get to return a POCO object from a json section via JsonConfigurationExtensions.
The simplest case:
IConfigurationBuilder builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostEnvironment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
IConfiguration configuration = builder.Build();
return configuration.GetSection("ServerConfiguration").Get<ServerConfiguration>();
And a nested POCO:
public class ServerConfiguration
{
public Authentication Authentication { get; internal set; }
}
public class Authentication
{
public DatabaseConfiguration UserDatabase { get; internal set; }
}
public class DatabaseConfiguration
{
public string ConnectionString { get; internal set; }
public string DatabaseName { get; internal set; }
}
The result is a null object.
In order to "clean up" my code at inception, I actually did not include the set property declarations as it wasn't needed in previous Json to POCO handlers. However, even when declaring these handlers (typically non-public) the ASP.NET implementation for Json file processing was always returning null although retrieving the individual key pairs from the section was successful.
Upvotes: 3
Views: 660
Reputation: 51
The answer was buried in a response in the ASP.NET forum: https://github.com/aspnet/Configuration/issues/394#issuecomment-444683884
The resulting change in the code:
1) Make sure there is a declaration of a set handler (internal, protected, private).
2) Specify BindOptions => BindNonPublicProperties.
return configuration.GetSection("ServerConfiguration")
.Get<ServerConfiguration>(c => c.BindNonPublicProperties = true);
Upvotes: 2