3

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.

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.