Recipe 6.3 · C#
Environments Without web.config Transforms
Problem
Each environment needs different settings: a local database for developers, a test server for
QA, production values in production. The legacy approach was Web.Release.config transforms
applied at publish time, which meant a different build per environment, and production settings
that lived in the repository. Worse, when something misbehaves you can't tell which file a value
came from.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
<!-- Not this: environment values baked in at build time. -->
<appSettings>
<add key="ApiUrl" value="https://api.example.com"
xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="SmtpPassword" value="Pr0dP@ss!"
xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>
The improved recipe
Build once, configure per environment at run time. The environment name selects an optional
appsettings.{Environment}.json, and environment variables or a vault supply the secrets. Log a
short summary at startup so you can always see what the app loaded.
appsettings.json defaults shared by every environment
appsettings.Development.json local machine values, no secrets
appsettings.Staging.json test server values, no secrets
appsettings.Production.json production values, no secrets
using System;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Configuration;
public static class ConfigurationDiagnostics
{
/// <summary>Logs the environment and configuration sources,
/// never values.</summary>
public static void LogSummary(
IConfiguration configuration,
IHostEnvironment environment,
ILogger logger)
{
logger.LogInformation(
"Starting {Application} in {Environment} from {ContentRoot}",
environment.ApplicationName,
environment.EnvironmentName,
environment.ContentRootPath);
if (configuration is not IConfigurationRoot root)
{
return;
}
foreach (IConfigurationProvider provider in root.Providers)
{
logger.LogInformation(
"Configuration source: {Provider}", provider);
}
}
/// <summary>Returns the source that supplies a key. The last
/// provider that has the key wins.</summary>
public static string? FindSource(
IConfigurationRoot root, string key)
{
return root.Providers
.Reverse()
.FirstOrDefault(p => p.TryGet(key, out _))
?.ToString();
}
}
Usage in Program.cs:
WebApplication app = builder.Build();
ConfigurationDiagnostics.LogSummary(
app.Configuration, app.Environment, app.Logger);
How it works
The host reads the environment name from ASPNETCORE_ENVIRONMENT (web apps) or
DOTNET_ENVIRONMENT (any host). If neither is set, the environment is Production, which is the
safe default: a forgotten variable on a server never turns on developer exception pages.
WebApplication.CreateBuilder loads sources in this order, later ones winning:
appsettings.jsonappsettings.{Environment}.json- User secrets (Development only)
- Environment variables
- Command-line arguments
The same build output runs everywhere. Moving a release from staging to production changes the environment variable, not the binaries. The environment JSON files carry only the values that differ and contain no secrets, so they are safe to commit.
The startup summary logs lines such as JsonConfigurationProvider for 'appsettings.Production.json'
(Optional). When someone asks "why is production calling the test API?" the answer is usually
that the environment name was wrong or the file wasn't deployed, and the first ten lines of the
log now say so. FindSource answers the more specific question of which source won for one key,
which is handy in a diagnostics endpoint protected for administrators.
Variations and pitfalls
- In IIS, set the environment with an
<environmentVariable>element under<aspNetCore>inweb.config, or on the application pool. Publish profiles can write it for you. - You can use any environment name:
IsEnvironment("UAT")works, and so doesappsettings.UAT.json. Keep the list short. root.GetDebugView()prints every key, its value and its source. It's great on a developer machine and a disaster in a production log, because it prints secrets too.- Don't branch on the environment throughout the code (
if (env.IsProduction()) ...). Put the difference in configuration and keep one code path. - Remember that
reloadOnChangeis on by default for the JSON files in a host. Editingappsettings.jsonon a live server changesIOptionsMonitorvalues within seconds, which is useful for log levels and surprising for anything else.