Search code examples
c#.net-coreconfigurationasp.net-core-mvcappsettings

How to get nested appSettings value(s) strongly typed?


I have this configuration in an ASP.NET Core MVC app:

"CustomSite": {
    "Management": {
        "Confined": {
            "DefaultUILanguage": "en-GB",
            "Id": "123456",
            "MainDomLock": "True"
        },
        "ThirdParty": {
            "Results": {
                "Team": {
                    "Settings": {
                        "InformtionId": "123",
                        "AdminKey": "456"
                    }
                }
            }
        },

I want to have ThirdParty settings strongly typed. I then created this class here:

public class TeamSettings
{
    public string? InformationId { get; set; } = string.Empty;
    public string AdminKey { get; set; } = string.Empty;
}

I registered it

....Services.Configure<TeamSettings>(builder.Configuration.GetSection(nameof(TeamSettings)));

But when I attempt to get the value - it's always null - why?

IOptions<TeamSettings> teamSettings

then

teamSettings.Value.InformationId; // is always null

After some reading, I tried to change it to:

Services.Configure<TeamSettings>(builder.Configuration
    .GetSection("CustomSite")
    .GetSection("Management")
    .GetSection("ThirdParty")
    .GetSection("Results")
    .GetSection(nameof(TeamSettings)));

However that, too, is null.

What am I doing wrong?

I've checked other similar threads and docs but I'm clearly missing something, somewhere?


Solution

  • You need to:

    builder.Services.Configure<TeamSettings>(builder.Configuration
        .GetSection("CustomSite:Management:ThirdParty:Results:Team:Settings"));
    

    also, you have a typo InformationId and InformtionId...