Val
Val

Reputation: 1822

Can't read a custom settings JSON file

I added a custom JSON file with settings that I want to read in my .NET8 API. The standard appsettings.json file is read correctly but the custom secrets.json is not. The section I'm trying to read from it is always null. What am I doing wrong?

Program.cs:

var env = ConfigHelpers.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
                .AddJsonFile("secrets.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .AddCommandLine(args)
                .Build();

var configurationModel = config.GetSection(ConfigurationModel.SectionName).Get<ConfigurationModel>();
builder.Services.AddSingleton(configurationModel);

var secretsConfigurationModel = config.GetSection(SecretsConfigModel.SectionName).Get<SecretsConfigModel>();
builder.Services.AddSingleton(secretsConfigurationModel);

The class for reading from the standard appsettings.json file:

public class ConfigurationModel
{
    public const string SectionName = "AppConfig";
    public int SaverDelay { get; set; } = 10000;
    public int SaverBatchSize { get; set; } = 1000;
}

My custom class for reading from secrets.json:

public class SecretsConfigModel
{
    public const string SectionName = "Encryption";
    public string TokenSecretSalt { get; set; }
}

The secrets.json file:

{
  "Encryption": [
    { "TokenSecretSalt": "c48mt45ty487tg47y85mh8g5h6587h6g586gh568756" }
  ]
}

Upvotes: 1

Views: 79

Answers (1)

dbc
dbc

Reputation: 116741

The value of the "Encryption" property in your secrets.json file is an array of objects:

{
  "Encryption": [ // Array start
    { "TokenSecretSalt": "c48mt45ty487tg47y85mh8g5h6587h6g586gh568756" }
  ] // Array end
}

You can use a collection to bind to it, e.g. SecretsConfigModel [] or List<SecretsConfigModel>:

var secretsConfigurationModel  = 
    config.GetSection(SecretsConfigModel.SectionName)
    .Get<SecretsConfigModel []>()
    .FirstOrDefault(); // Use SingleOrDefault() if there cannot be more than one.

Demo fiddle #1 here.

Alternatively you could eliminate the array nesting from your JSON and your current code will work:

{
  "Encryption": { 
    "TokenSecretSalt": "c48mt45ty487tg47y85mh8g5h6587h6g586gh568756" 
  }
}

Demo fiddle #2 here.

Upvotes: 1

Related Questions