Skip to content

4.7 — Environments and ASPNETCORE_ENVIRONMENT

← Roadmap · Section: 4. Fundamentals and Application Startup Prev: 4.6 Application lifecycle · Next: 4.8 launchSettings.json

Markers: 🔥 · Confidence: 🔴 · Last reviewed: —


TL;DR

An environment is a named context your app runs in — Development, Staging, Production — that changes its configuration and behaviour without changing its code.

  • Set by the ASPNETCORE_ENVIRONMENT environment variable. If it is missing, the app assumes Production.
  • It selects which appsettings.{Environment}.json file is layered on top of the base settings.
  • The names are just strings. Development is spelled exactly that way, and a typo silently gives you Production behaviour.

Definitions

Term What it is What it means
Environment a named context Which deployment this is. Changes config and behaviour, not code.
ASPNETCORE_ENVIRONMENT an environment variable Sets the environment name. The primary mechanism.
DOTNET_ENVIRONMENT an environment variable The same, for non-web .NET apps. ASPNETCORE_ wins if both are set.
Development a built-in name Local machine. Detailed errors, developer tools on.
Staging a built-in name Production-like environment for final testing.
Production a built-in name Live. The default when nothing is set.
IWebHostEnvironment an interface Injectable. Tells you the environment name and paths.
IsDevelopment() an extension method Case-insensitive check for the name "Development".
IsEnvironment("x") an extension method Check for any custom name.
appsettings.{Env}.json a config file Layered on top of appsettings.json for that environment.
launchSettings.json a dev-only file Sets the variable when launching from an IDE or dotnet run. Never deployed — see 4.8.
Developer exception page middleware Full stack traces in the browser. Development only, deliberately.

The concept

What problem it solves

The same compiled application needs to behave differently depending on where it is running:

  • On your machine you want full stack traces in the browser, a local database, and Swagger enabled.
  • In production you want a generic error page, the real database, no schema exposed, and logging going to a central system.

You could branch on a compile-time flag, but then dev and production are different builds — so what you tested is not what you shipped.

Environments solve it differently: one build, different configuration. The binary is identical everywhere. Only the settings it reads change.

A picture: the same car, driven in different countries. Same vehicle; you adjust the headlights and the speedometer units. You do not manufacture a different car.

How the app knows which one it is in

One environment variable:

ASPNETCORE_ENVIRONMENT=Production

⚠️ If it is not set, ASP.NET Core assumes Production.

That default is deliberate and it is the safe choice — an app accidentally deployed without configuration behaves cautiously rather than exposing stack traces. But it catches people out locally: forget to set it and you get production behaviour on your own machine, wondering why your errors are unhelpful.


How it works

The simple version — checking the environment

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();     // full stack traces in the browser
    app.MapOpenApi();                    // expose the API schema
}
else
{
    app.UseExceptionHandler("/error");   // generic error page
    app.UseHsts();                       // force HTTPS for future visits
}

Available checks:

app.Environment.IsDevelopment();
app.Environment.IsStaging();
app.Environment.IsProduction();
app.Environment.IsEnvironment("QA");        // custom names
app.Environment.EnvironmentName;            // the raw string

These are case-insensitive, so development matches IsDevelopment(). That is one small mercy — but the file names are case-sensitive on Linux, which is not.

You can inject it into any service too:

public class EmailSender(IWebHostEnvironment env, ILogger<EmailSender> logger)
{
    public Task SendAsync(string to, string body)
    {
        if (!env.IsProduction())
        {
            logger.LogInformation("Would have emailed {To}", to);
            return Task.CompletedTask;      // never email real users from staging
        }

        return _client.SendAsync(to, body);
    }
}

How it actually works — the configuration layering

This is the mechanism that does the real work.

At startup, WebApplication.CreateBuilder loads configuration in a specific order, and later sources override earlier ones:

1. appsettings.json                      ← base, always loaded
2. appsettings.{Environment}.json        ← layered on top
3. User Secrets                          ← Development only
4. Environment variables
5. Command-line arguments                ← highest priority

So with ASPNETCORE_ENVIRONMENT=Staging:

// appsettings.json — shared defaults
{
  "Logging": { "LogLevel": { "Default": "Information" } },
  "ConnectionStrings": { "Default": "Server=localhost;Database=App" },
  "Features": { "EnableNewCheckout": false }
}
// appsettings.Staging.json — only what differs
{
  "Logging": { "LogLevel": { "Default": "Debug" } },
  "ConnectionStrings": { "Default": "Server=staging-sql;Database=App" }
}

The app sees Debug logging, the staging connection string, and EnableNewCheckout: false inherited from the base file.

Only put the differences in the environment file. Copying the whole base file into each environment file means every change has to be made in four places, and they drift.

See 7.1.

⚠️ The IsDevelopment() security trap

This is the one worth being careful about:

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

The developer exception page shows the full stack trace, source code snippets, the request headers, and all environment variables in the browser. That is exactly what you want locally and a serious information disclosure in production — connection strings and API keys are routinely visible in those environment variables.

So the danger is: anything that accidentally sets ASPNETCORE_ENVIRONMENT=Development in a deployed environment immediately exposes your secrets to anyone who can trigger an error.

That happens more often than you would expect — a copied Dockerfile, a Helm value that was never overridden, a base image with the variable baked in.

Defence in depth: do not rely solely on the environment check for anything genuinely sensitive. A production deployment can also verify the assumption at startup:

if (app.Environment.IsDevelopment() && builder.Configuration["DeployRing"] == "prod")
    throw new InvalidOperationException(
        "Development environment on a production deployment — refusing to start.");

Failing to start is far better than running with debug tooling exposed.

The deeper detail — custom environments

The three built-in names are just strings, and you can use your own:

ASPNETCORE_ENVIRONMENT=QA
if (app.Environment.IsEnvironment("QA"))
{
    app.UseMiddleware<TestDataSeedingMiddleware>();
}

appsettings.QA.json is then picked up automatically — the layering uses whatever name you set.

⚠️ But custom names are not "development-like". IsDevelopment() returns false for QA, so anything gated behind it is off. If you want QA to behave like development for tooling, you must say so explicitly:

var isDevLike = app.Environment.IsDevelopment() || app.Environment.IsEnvironment("QA");

Keep the list short. Every extra environment is another config file to maintain and another path that is rarely tested. Three or four is usually enough.

Setting it in each place

# Locally — the shell
export ASPNETCORE_ENVIRONMENT=Development       # Linux/macOS
$env:ASPNETCORE_ENVIRONMENT="Development"       # PowerShell

# Docker
ENV ASPNETCORE_ENVIRONMENT=Production

# docker-compose
environment:
  - ASPNETCORE_ENVIRONMENT=Staging

# Kubernetes
env:
  - name: ASPNETCORE_ENVIRONMENT
    value: "Production"

# Azure App Service — an application setting of the same name

And in development, launchSettings.json sets it for you when you press F5 or run dotnet run:

{
  "profiles": {
    "MyApp": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

⚠️ That file is development-only and never deployed. People assume it configures production and are surprised when nothing takes effect. See 4.8.


Code

A realistic environment-aware startup:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Different database per environment, driven by configuration not code
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

// Detailed EF logging is expensive and leaks parameter values — dev only
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddDbContext<AppDbContext>(options =>
        options.EnableSensitiveDataLogging().EnableDetailedErrors());
}

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.MapOpenApi();                          // never in production
}
else
{
    app.UseExceptionHandler("/error");         // generic, no internals leaked
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();

Note EnableSensitiveDataLogging. It writes parameter values into your logs, so a query filtering by email address logs that email address. Genuinely useful when debugging locally, and a data-protection incident in production. The environment check is the only thing keeping those apart.


Interview questions

Q: How does ASP.NET Core know which environment it is running in?

From the ASPNETCORE_ENVIRONMENT environment variable. If it is not set, the framework defaults to Production, which is a deliberately safe choice — an app deployed without configuration behaves cautiously rather than exposing debug tooling. The name selects which appsettings.{Environment}.json file gets layered on top of the base appsettings.json, and you can check it in code through IWebHostEnvironment with IsDevelopment, IsProduction or IsEnvironment for custom names.

Q: What is the risk of the developer exception page?

It shows the full stack trace, source snippets, request headers and all environment variables in the browser. Environment variables routinely include connection strings and API keys, so if anything accidentally sets the environment to Development on a deployed system, triggering any error hands an attacker your secrets. That happens through copied Dockerfiles or Helm values that were never overridden more often than people expect. Beyond gating it on the environment check, I would have production refuse to start if it detects a Development environment name, because failing loudly beats running with debug tooling exposed.

Q: How do you configure different settings per environment?

Through configuration layering rather than code branching. appsettings.json holds shared defaults, and appsettings.{Environment}.json is layered on top with only the values that differ — so the staging file might override just the connection string and log level. Above those sit environment variables and command-line arguments, which take higher priority, and that is where secrets belong in a deployed environment. The point is that it is the same compiled binary everywhere, so what you tested is what you shipped.

Q: Can you have environments other than the three built-in ones?

Yes — the names are just strings, so setting ASPNETCORE_ENVIRONMENT=QA works and appsettings.QA.json is picked up automatically. The catch is that IsDevelopment() returns false for a custom name, so anything gated behind that check is off, and you have to opt into development-like behaviour explicitly. I would also keep the list short, because every extra environment is another config file to maintain and another code path that is rarely exercised.


Traps ⚠️

  • Missing ASPNETCORE_ENVIRONMENT means Production. Safe in deployment, confusing locally.
  • The developer exception page leaks environment variables, which usually contain secrets.
  • Environment names are case-insensitive in code but file names are case-sensitive on Linux. appsettings.production.json is silently ignored on Linux when the environment is Production.
  • launchSettings.json is development-only and never deployed.
  • Custom environments are not development-like. IsDevelopment() returns false for QA.
  • Copying the whole base file into each environment file causes drift. Override only the differences.
  • EnableSensitiveDataLogging writes parameter values to logs. Never outside development.
  • Do not put secrets in appsettings.{Environment}.json. Those files are in source control — see 17.7.


Sources