ASP.NET Core environments: how the environment name is resolved (ASPNETCORE_ENVIRONMENT, DOTNET_ENVIRONMENT, --environment, default Production), IHostEnvironment and IsDevelopment/IsProduction/IsEnvironment, what changes in Development (developer exception page, user secrets, DI validation), appsettings.{Environment}.json selection, launchSettings.json, and what belongs outside appsettings.
The environment name tells the host which settings and behaviours to use. It is read from ASPNETCORE_ENVIRONMENT or DOTNET_ENVIRONMENT (or --environment), and if nothing is set it defaults to Production, which is the safe default. For web apps, ASPNETCORE_ENVIRONMENT wins when both are set.
The name selects appsettings.{Environment}.json and is exposed through IHostEnvironment (IsDevelopment(), IsProduction(), IsEnvironment("Staging")). In Development, CreateBuilder also loads user secrets, shows the developer exception page and validates DI scopes. Locally the name usually comes from launchSettings.json.
Never put secrets or per-deployment values in committed appsettings files. The trade-off: environment files are convenient, but every if (IsProduction()) branch is code you never ran before production.
"The environment is just a name,
Development,Staging,Productionor anything you like, and the host reads it at start-up fromASPNETCORE_ENVIRONMENTorDOTNET_ENVIRONMENT, or from--environmenton the command line. If nothing sets it, it's Production. That default is deliberate: forgetting to set it should give you the locked-down behaviour, not the developer exception page with stack traces.The name does three things. First, it picks the extra file:
appsettings.Staging.jsonis loaded on top ofappsettings.json. Second,CreateBuilderchanges some defaults in Development: user secrets are loaded, the developer exception page is used for unhandled errors, and the DI container validates scopes and every registration on build. Third, I can branch on it withIHostEnvironment.IsDevelopment(), for example to map Swagger UI only locally. For a web appASPNETCORE_ENVIRONMENTwins overDOTNET_ENVIRONMENT; a worker service built withHost.CreateApplicationBuilderonly looks atDOTNET_ENVIRONMENT. Locally,launchSettings.jsonsets Development for me, and that file is never deployed.The mistake I see is treating
appsettings.Production.jsonas the place for production secrets because 'it only runs in production'. It's still committed and baked into the image. Secrets come from Key Vault or the platform. The other mistake is scatteringif (env.IsProduction())through business code: I'd rather have a configuration value likeEmail:UseSandboxthat each environment sets, so the same code path runs everywhere."
| Source | Wins over | Notes |
|---|---|---|
--environment Staging |
Everything below | Command line |
ASPNETCORE_ENVIRONMENT |
DOTNET_ENVIRONMENT |
Web apps only |
DOTNET_ENVIRONMENT |
Default | Web apps and worker services |
| Default | Production |
CreateBuilder| Behaviour | Development | Other environments |
|---|---|---|
| User secrets loaded | Yes (if the project has a UserSecretsId) |
No |
| Unhandled exceptions | Developer exception page | Your UseExceptionHandler |
DI ValidateScopes / ValidateOnBuild |
On | Off |
appsettings.Development.json |
Loaded | Not loaded |
| Value | Where it belongs |
|---|---|
| Defaults, log levels, feature defaults | appsettings.json |
| Non-secret per-environment differences (URLs of test services) | appsettings.{Env}.json |
| Passwords, API keys, connection strings with credentials | User secrets locally; Key Vault, managed identity or platform secrets in Azure |
| Per-deployment values (instance name, region) | Environment variables from the platform |
A team shipped appsettings.Production.json with a third-party API key "because only production reads it". It was in the git history and in every image pushed to the registry; rotating the key and moving it to Key Vault took a day. Afterwards, a secret-scanning step in the pipeline blocked any commit with a key-shaped value in appsettings*.json.
Checks whether the candidate understands how an app knows where it is running and keeps environment differences safe.
Green flags
ASPNETCORE_ENVIRONMENT over DOTNET_ENVIRONMENT.Red flags
launchSettings.json is used in production.appsettings.Production.json.Before the app configuration is built, the host reads host configuration: environment variables prefixed DOTNET_, then (for web apps) ASPNETCORE_, then command-line args. The prefix is stripped, so ASPNETCORE_ENVIRONMENT becomes the key environment. Because ASPNETCORE_ is added later, it wins.
DOTNET_ENVIRONMENT=Staging ┐
ASPNETCORE_ENVIRONMENT=Test ├─► host config "environment" = "Test"
(no --environment) ┘ │
▼
IHostEnvironment.EnvironmentName = "Test"
│
▼
loads appsettings.json + appsettings.Test.json
IWebHostEnvironment adds WebRootPath to IHostEnvironment. The Is... helpers are extension methods that compare the name case-insensitively. Names are free strings: IsEnvironment("LoadTest") is valid, and appsettings.LoadTest.json is picked up automatically.
launchSettings.json is read by dotnet run, Visual Studio and Rider. Each profile sets environment variables, commonly ASPNETCORE_ENVIRONMENT=Development. It is not copied to the publish output, so a deployed app falls back to whatever the platform sets, or Production.
The developer exception page shows stack traces, source lines and headers. If an unset variable meant Development, a forgotten setting would leak internals. Defaulting to Production fails safe.
<environment include="Development"> tag helper.builder.Environment.IsDevelopment() before Build(), to decide which services to register.WebApplicationFactory lets you call builder.UseEnvironment("Testing").app.Environment.EnvironmentName; confirm it is Production.DOTNET_ENVIRONMENT=Staging and ASPNETCORE_ENVIRONMENT=Test; see which wins.appsettings.Test.json with a different value and check it loads only in Test.launchSettings.json is not in the output folder.Branching on the environment only at the composition root, and letting configuration carry the differences.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddOpenApi();
// The behaviour difference lives in configuration, not in if (IsProduction()) checks in services
builder.Services.AddOptions<EmailOptions>().BindConfiguration(EmailOptions.Section);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi(); // docs only on developer machines
}
else
{
app.UseExceptionHandler(); // ProblemDetails, no stack traces
app.UseHsts();
}
app.Logger.LogInformation("Running as {Environment}", app.Environment.EnvironmentName);
app.Run();
public sealed class EmailOptions
{
public const string Section = "Email";
public bool UseSandbox { get; init; } = true; // safe default; production sets false
}
// appsettings.Production.json: non-secret differences only
{
"Email": { "UseSandbox": false },
"Logging": { "LogLevel": { "Default": "Warning" } }
}
appsettings.Production.json. Why it is wrong: The file is committed and shipped in every build. Instead: Use Key Vault, managed identity or platform secrets.DOTNET_ENVIRONMENT on a web app that also has ASPNETCORE_ENVIRONMENT from a base image. Why it is wrong: ASPNETCORE_ENVIRONMENT wins, so your change does nothing. Instead: Set one variable consistently, preferably ASPNETCORE_ENVIRONMENT for web apps.launchSettings.json in a deployed app. Why it is wrong: It is never published. Instead: Set variables in the hosting platform.if (env.IsProduction()) through services. Why it is wrong: The production path is never exercised before production. Instead: Model the difference as a configuration value.appsettings.production.json on Linux. Why it is wrong: File names are case-sensitive on Linux, so the file is not found. Instead: Match the environment name's casing exactly.Keep the number of environments and environment files small. Every appsettings.{Env}.json is a copy that drifts, so I keep only the real differences there and make Production the baseline that needs no file at all, with safe defaults in appsettings.json. The environment name should change settings, not code paths: the only IsDevelopment() checks I accept are in Program.cs, for things like the developer exception page and API docs.
Properties/launchSettings.json defines launch profiles for local development: how to start the app, which URLs, and which environment variables. Visual Studio, Rider, VS Code with C# Dev Kit and dotnet run all read it, but it is not published. In this file I would flag: secrets are committed (a production connection string and API key), so they must be rotated now and moved to user secrets; the environment is Production, which switches on production behaviour and turns off user secrets, and combined with the production connection string means a developer's F5 talks to the live database; and it binds to 0.0.0.0 over plain HTTP, exposing the app to the network. I would replace it with HTTPS and HTTP profiles on localhost using Development, and add a separate production-like profile only if someone needs to test production behaviour against non-production resources.
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
Last updated 23 Nov 2026.