I’ve been working in Java the past few years and starting back into .NET now. I’m struggling with getting my configs working as I’d like.
I want to have this structure:
appsettings.json
: default settings that are env agnosticappsettings.local.json
: local specific config overridesappsettings.dev.json
: dev specific config overridesappsettings.stage.json
: stage specific config overrides
The issue I’m running into is that when the appsettings.local.json
file is used (or any other env specific file), then the base values in the appsettings.json
file aren’t loaded even if the appsettings.local.json
file didn’t override them.
Config setup code:
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
configuration
.AddEnvironmentVariables()
.Build();
appsettings.json
:
{
...
"Mctv": {
"Port": "8080",
"CORS": {
...
appsettings.local.json
:
{
...
"Mctv": {
"Run-Environment": "local",
"CORS": {
...
Note that the Port
setting isn’t specified in the appsettings.local.json
file, I want it to just use the value in the appsettings.json
file.
How do I set this up so that the env agnostic config in appsettings.json
is honored when not overridden by a value in an env specific config file?
Right now when I run with
"ASPNETCORE_ENVIRONMENT": "local"
only the values in the application.local.json
file are used.
EDIT
I’ve seen some posts online that state to do something like this:
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
configuration
.AddEnvironmentVariables()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", reloadOnChange: true, optional: false)
.AddJsonFile($"appsettings.{environmentName}.json", reloadOnChange: true, optional: true)
.Build();
But I get the same behavior when I tried that.
2
Make sure you have set “Copy to output directory” as “Copy always”/”Copy if newer” for all settings file:
Without it, they won’t be copied alongside compiled files, and thus the code won’t find it.
As a debugging process, you could specify that environment specific settings file is not optional and observe if exceptions are thrown.
Here’s reference SO post.