📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do environments work in ASP.NET Core? Explain ASPNETCORE_ENVIRONMENT versus DOTNET_ENVIRONMENT, what IsDevelopment() changes, how environment-specific appsettings files are picked, and what should never go in appsettings.json.

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.

Junior Theory Beginner appsettings aspnet-core configuration environments ihostenvironment

🎯 Key points

  • The environment name comes from host configuration: --environment, then ASPNETCORE_ENVIRONMENT, then DOTNET_ENVIRONMENT; if none is set it is Production
  • Web apps (WebApplication.CreateBuilder) read both prefixes and ASPNETCORE_ENVIRONMENT wins; worker services built with Host.CreateApplicationBuilder read only DOTNET_ENVIRONMENT
  • IHostEnvironment.EnvironmentName drives appsettings.{EnvironmentName}.json; the name is a free string, matched case-insensitively by IsEnvironment but file names are case-sensitive on Linux
  • Development turns on user secrets, the developer exception page and DI ValidateScopes/ValidateOnBuild
  • launchSettings.json sets Development for local runs only; it is never deployed
  • Secrets go in user secrets locally and Azure Key Vault with managed identity (or passwordless Entra ID auth) when deployed, never in committed appsettings files
  • Prefer configuration values over if (IsProduction()) branches, so the same code path is tested in every environment

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The environment is just a name, Development, Staging, Production or anything you like, and the host reads it at start-up from ASPNETCORE_ENVIRONMENT or DOTNET_ENVIRONMENT, or from --environment on 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.json is loaded on top of appsettings.json. Second, CreateBuilder changes 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 with IHostEnvironment.IsDevelopment(), for example to map Swagger UI only locally. For a web app ASPNETCORE_ENVIRONMENT wins over DOTNET_ENVIRONMENT; a worker service built with Host.CreateApplicationBuilder only looks at DOTNET_ENVIRONMENT. Locally, launchSettings.json sets Development for me, and that file is never deployed.

The mistake I see is treating appsettings.Production.json as 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 scattering if (env.IsProduction()) through business code: I'd rather have a configuration value like Email:UseSandbox that each environment sets, so the same code path runs everywhere."


How the name is resolved (web app)

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

What changes in Development with 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

What goes where

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands how an app knows where it is running and keeps environment differences safe.

Green flags

  • Knows the default is Production and why.
  • Explains the precedence of ASPNETCORE_ENVIRONMENT over DOTNET_ENVIRONMENT.
  • Lists what changes in Development (user secrets, exception page, DI validation).
  • Keeps secrets out of every appsettings file.

Red flags

  • Thinks launchSettings.json is used in production.
  • Stores production secrets in appsettings.Production.json.
  • Uses environment checks throughout business logic.

📚 Learn in depth

1. Where the environment comes from

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

2. IHostEnvironment

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.

3. launchSettings.json

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.

4. Why the default is 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.

5. Other places the name shows up

  • Razor's <environment include="Development"> tag helper.
  • builder.Environment.IsDevelopment() before Build(), to decide which services to register.
  • Test hosts: WebApplicationFactory lets you call builder.UseEnvironment("Testing").

Try it yourself

  1. Run an app with no variables and log app.Environment.EnvironmentName; confirm it is Production.
  2. Set both DOTNET_ENVIRONMENT=Staging and ASPNETCORE_ENVIRONMENT=Test; see which wins.
  3. Add appsettings.Test.json with a different value and check it loads only in Test.
  4. Throw from an endpoint in Development and in Production and compare the responses.
  5. Publish the app and confirm launchSettings.json is not in the output folder.

💻 Code

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" } }
}

⚠ Common mistakes

  • Mistake: Putting production secrets in 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.
  • Mistake: Assuming the environment defaults to Development. Why it is wrong: It defaults to Production, so a test server without the variable runs with production settings. Instead: Set the variable explicitly in every deployed environment.
  • Mistake: Setting 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.
  • Mistake: Relying on launchSettings.json in a deployed app. Why it is wrong: It is never published. Instead: Set variables in the hosting platform.
  • Mistake: Scattering 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.
  • Mistake: Mismatched file names such as 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions launchSettings.json setting the environment locally. Why: Checks they know what launchSettings.json does and that it is not deployed.
    How to answer

    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.

  2. When: Candidate mentions the DI validation that runs in Development. Why: Checks the wider picture of what CreateBuilder sets up, including ValidateOnBuild.
    How to answer

    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.

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me