ASP.NET Core MVC Intermediate

Development, Staging and Production environments

Your app behaves differently on your laptop and on the live server: detailed errors locally, friendly error pages in production, different databases. ASP.NET Core handles this with named environments. This lesson explains how the environment is chosen and how to use it.

How the environment shapes the app
  1. StartEnvironment is setASPNETCORE_ENVIRONMENT=Development (from launchSettings.json locally)
  2. Step 2Host reads it at startupNo value means Production
  3. Step 3Settings file loadedappsettings.Development.json overrides appsettings.json
  4. Step 4Program.cs branchesif (!app.Environment.IsDevelopment()) use the error page and HSTS
  5. EndViews adapt<environment include="Development"> shows dev-only markup

The idea in plain words

The environment is just a name, read from the ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT) variable when the app starts. The three standard names are Development, Staging and Production. When you run from Visual Studio or with dotnet run, launchSettings.json sets Development. On a server where nothing is set, the app runs as Production, which is the safe default.

In Development, ASP.NET Core shows the detailed developer exception page and loads user secrets. In Production you show a friendly error page and turn on HSTS.

Example

C#
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    // detailed errors are shown automatically in Development
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

if (app.Environment.IsEnvironment("Staging"))
{
    app.Logger.LogInformation("Running in Staging");
}

In views

Razor
<environment include="Development">
    <link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>

Common mistakes

  • Setting ASPNETCORE_ENVIRONMENT=Development on a public server, which exposes detailed error pages.
  • Expecting launchSettings.json to affect the deployed app; it is only for local runs.
  • Putting production secrets into appsettings.Production.json in source control.

Interview question

How does ASP.NET Core determine the current environment, and what is the default?

At startup the host reads the DOTNET_ENVIRONMENT and ASPNETCORE_ENVIRONMENT environment variables (ASPNETCORE_ENVIRONMENT takes precedence for web apps), or a value set in code or on the command line. If no value is set, the environment is Production. Locally, launchSettings.json usually sets Development for the run profile.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.