TExcelTAD
Home › ASP.NET Core › Environments

Environments

The same application runs on your laptop, on a test server and in production — but it should not behave identically everywhere. In development you want detailed error pages and verbose logs; in production you want generic error responses, HTTPS redirection and HSTS. ASP.NET Core models this with a named environment.

Setting the environment

The environment name comes from the ASPNETCORE_ENVIRONMENT variable (or DOTNET_ENVIRONMENT if that one is not set). Three names have built-in helpers, but any name is allowed:

Name Helper Typical use
Development IsDevelopment() your machine
Staging IsStaging() pre-production testing
Production IsProduction() live users — the default when nothing is set
anything else IsEnvironment("QA") custom stages

When you use dotnet run, the variable usually comes from Properties/launchSettings.json, which the template creates for you:

json
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Note: launchSettings.json is a local development file only. It is used by dotnet run, Visual Studio and VS Code — it is never read on a server, so a published app runs as Production unless you set the variable there.

The startup log tells you which environment is active:

bash · try it yourself
$ dotnet run
Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/dev/TodoApi

To try another environment, override the profile with --no-launch-profile and set the variable yourself:

bash · try it yourself
$ ASPNETCORE_ENVIRONMENT=Staging dotnet run --no-launch-profile --urls http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Staging
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/dev/TodoApi

Branching on the environment in Program.cs

app.Environment (an IWebHostEnvironment) is available after Build(), and builder.Environment before it:

csharp
var builder = WebApplication.CreateBuilder(args);

if (builder.Environment.IsDevelopment())
{
    builder.Services.AddOpenApi();          // only expose API docs locally
}

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    // The developer exception page is on by default in Development
}
else
{
    app.UseExceptionHandler("/error");      // generic error response
    app.UseHsts();                          // tell browsers to always use HTTPS
}

app.UseHttpsRedirection();
app.MapGet("/env", (IWebHostEnvironment env) => new { env.EnvironmentName, env.ApplicationName });
app.Run();
bash · try it yourself
$ curl -s localhost:5000/env
{"environmentName":"Development","applicationName":"TodoApi"}

The helpers are just case-insensitive string comparisons on EnvironmentName. This plain C# version reproduces them and shows the "Production by default" rule:

csharp · try it yourself
using System;
using System.Collections.Generic;

foreach (var variable in new[] { "Development", "staging", null, "QA" })
{
    var env = new HostEnvironment(variable);
    Console.WriteLine(
quot;{variable ?? "(not set)",-12} -> {env.EnvironmentName,-12} dev={env.IsDevelopment(),-5} prod={env.IsProduction(),-5} qa={env.IsEnvironment("qa")}"); } class HostEnvironment { public string EnvironmentName { get; } public HostEnvironment(string? variable) => EnvironmentName = string.IsNullOrEmpty(variable) ? "Production" : variable; public bool IsEnvironment(string name) => string.Equals(EnvironmentName, name, StringComparison.OrdinalIgnoreCase); public bool IsDevelopment() => IsEnvironment("Development"); public bool IsProduction() => IsEnvironment("Production"); }
Development  -> Development  dev=True  prod=False qa=False
staging      -> staging      dev=False prod=False qa=False
(not set)    -> Production   dev=False prod=True  qa=False
QA           -> QA           dev=False prod=False qa=True

An unset variable falls back to Production, and comparisons ignore case — but a custom name like staging is still not Production.

Environment-specific configuration

The configuration system loads appsettings.{EnvironmentName}.json on top of appsettings.json. Put only the differences in the environment file:

json
// appsettings.Development.json
{
  "Logging": { "LogLevel": { "Default": "Debug" } },
  "ConnectionStrings": { "Default": "Data Source=dev.db" }
}
File Loaded when
appsettings.json always
appsettings.Development.json ASPNETCORE_ENVIRONMENT=Development
appsettings.Production.json ASPNETCORE_ENVIRONMENT=Production (or not set)
user secrets Development only

Environments in Razor views

MVC views and Razor Pages can render markup only in certain environments with the <environment> tag helper — handy for unminified scripts locally and minified bundles in production:

cshtml
<environment include="Development">
    <script src="~/js/site.js"></script>
</environment>
<environment exclude="Development">
    <script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>

Tip: Never decide security-relevant behaviour (like disabling authentication) based on a custom environment name typed by hand on a server. A typo silently becomes Production-like or worse — keep such switches in explicit configuration.

Test yourself

Which environment does a published ASP.NET Core app use if ASPNETCORE_ENVIRONMENT is not set?

  1. Development
  2. Staging
  3. Production
  4. It refuses to start

Where does dotnet run normally get ASPNETCORE_ENVIRONMENT=Development from?

  1. appsettings.json
  2. Properties/launchSettings.json
  3. The .csproj file
  4. Program.cs

With the environment set to Staging, which extra settings file is loaded?

  1. appsettings.Staging.json
  2. appsettings.Development.json
  3. staging.json
  4. None — only appsettings.json