Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Minimal API proper use of .AddJsonFile() with environment variables

I see .NET samples with, for example,

builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);

But in this article: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0 it says of that code:

"Settings in the MyConfig.json file override setting in the default configuration providers, including the Environment variables configuration provider and the Command-line configuration provider."

So does that mean:

  1. That you should just be aware, and be careful not to override values from environment variables

  2. That you now need to also explicitly read environment variables?

For example, I also see this pattern in sample code:

builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)       
    .AddJsonFile($"appsettings{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
    .AddEnvironmentVariables();

I assume that it's #1. Obviously I could test this, but figured that I could save myself and others the trouble by asking.

like image 915
Chris Harrington Avatar asked Aug 31 '25 17:08

Chris Harrington


1 Answers

Not exactly, settings in the JSON file override all other providers because it is the only provider configured.

When you append an environment setting provider at the end:

builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)       
    .AddJsonFile($"appsettings{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
    .AddEnvironmentVariables();

Then, this means JSON settings can be overridden by environment variables because it is the last one declared in code. Basically I think what the docs are trying to say is the order in which you declare your settings providers matters. So it all depends on what you are trying to achieve.

like image 187
beautifulcoder Avatar answered Sep 02 '25 07:09

beautifulcoder