Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 52 ยท Dependency Injection, Configuration and Logging

Environments and Secrets

Understand ASPNETCORE_ENVIRONMENT, what changes between Development and Production, and how to keep passwords and API keys out of source control with user secrets.

The same application runs in several places: on your laptop while you code, on a test server, on a staging copy that mirrors production, and finally in production. Each place needs slightly different behavior. You want detailed error pages and a local database on your laptop; you want terse errors, HTTPS enforcement and a real database in production. And you never want the production database password to be written in a file that sits in Git.

ASP.NET Core handles the first problem with environments and the second with secrets that live outside the code. This lesson explains both. It builds directly on configuration and options, which introduced the layered providers. Here we look at the layers that depend on the environment and the layers that hold sensitive values. Our runner has no real user profile or cloud, so the live examples use faithful stand-ins and say so; the commands for the real tools are shown read-only.

What an environment is

An environment is just a name. ASP.NET Core reads it from the environment variable ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT) when the host starts. Three names have built-in meaning:

Name Typical use
Development Your machine. Detailed errors, user secrets and extra validation are on.
Staging A pre-production copy for final checks.
Production The live system. This is the default when the variable is not set.

You are free to invent others, such as Testing or QA; you just check them with IsEnvironment("Testing"). The comparison is case-insensitive.

Code reads the name from builder.Environment (before the app is built) or app.Environment (after). The convenience methods IsDevelopment(), IsStaging() and IsProduction() are extension methods on IHostEnvironment.

The default is deliberately Production: forgetting to set anything on a server gives you the safe behavior, not the verbose one.

flowchart LR
    V["ASPNETCORE_ENVIRONMENT"] --> H["Host starts"]
    H --> E["Environment name"]
    E --> F["appsettings.{name}.json<br/>is loaded"]
    E --> D["Development-only features<br/>(secrets, developer exception page,<br/>scope validation)"]
    E --> C["Your own code:<br/>IsDevelopment() checks"]

One name decides which configuration file loads, which framework features switch on and which branches your own code takes.

What changes with the environment

Several things depend on the name, some automatically and some by convention:

  • Configuration layers. appsettings.{Environment}.json loads only when the name matches, and user secrets are loaded only in Development.
  • The developer exception page, shown in the error handling lesson, is automatic in Development only.
  • Dependency-injection validation (ValidateScopes and ValidateOnBuild) is on by default in Development, as seen in the DI lesson.
  • Static web assets and some diagnostic tooling are enabled in Development.
  • Your own branches, for example HSTS and HTTPS redirection only outside Development, or a seeded database only in Development.

Do not scatter if (env.IsDevelopment()) through business code. Prefer configuration: put the difference in appsettings.Development.json and let the code read an option. Reserve environment checks for wiring in Program.cs.

Seeing environments in action

The program below starts the host four times with different environment names. For the Staging run it also places an appsettings.Staging.json next to the app, so you can see that the extra file loads only for that environment. Finally, it sets the real ASPNETCORE_ENVIRONMENT variable the way a server would.

C# Environment names and environment files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Only the Staging run shows the staging banner; Testing (a name we invented) behaves like any other environment with no file of its own, and an unset variable means Production.

Setting the environment

On a real machine you set the variable in the place that starts the process:

TEXT
# local shell (PowerShell)
$env:ASPNETCORE_ENVIRONMENT = "Development"

# Linux/macOS shell
export ASPNETCORE_ENVIRONMENT=Development

# docker run
docker run -e ASPNETCORE_ENVIRONMENT=Staging myapp

# Kubernetes / systemd / cloud app settings: an environment entry named ASPNETCORE_ENVIRONMENT

During local development, Properties/launchSettings.json (covered in project anatomy) defines profiles, and dotnet run uses one of them to set ASPNETCORE_ENVIRONMENT=Development. That file is for your machine only; it is not used when the app is published.

Why secrets need their own place

Configuration values come in two kinds. A page size or a feature flag is a harmless setting. A database password, an API key or a signing key is a secret, and a leaked secret is an incident.

The rule is short: secrets must never be committed to source control. Not in appsettings.json, not in a "temporary" test, not in an appsettings.Development.json you promise to delete later. Git remembers forever, and repositories get shared, forked and scraped by bots within minutes of a push.

So where do secrets live? It depends on the environment:

flowchart TB
    subgraph Dev["Development (your machine)"]
        US["User secrets<br/>file outside the project"]
    end
    subgraph Prod["Staging and Production"]
        EV["Environment variables"]
        KV["Key vault or secret manager"]
        MF["Mounted secret files<br/>(Docker, Kubernetes)"]
    end
    US --> CFG["IConfiguration"]
    EV --> CFG
    KV --> CFG
    MF --> CFG
    CFG --> APP["Your options classes"]

Every store feeds the same IConfiguration, so application code does not know or care where a secret came from.

User secrets in development

User secrets keep development secrets in a JSON file in your user profile, outside the project folder, so it can never be committed by accident. The project stores only a random id that links it to that file. This is read-only because it needs the .NET CLI and a real profile folder:

TEXT
dotnet user-secrets init
dotnet user-secrets set "ConnectionStrings:Default" "Server=localhost;Database=shop;User Id=dev;Password=dev-only-pass"
dotnet user-secrets list

The WebApplication.CreateBuilder defaults add the provider automatically only in Development, and the values then override appsettings.json. In code, you read them like any other setting. Two caveats matter: the file is not encrypted, it is just kept out of the repository, and it exists only on your machine, so it is for development only.

Environment variables in production

The simplest production mechanism is an environment variable named with __ for the separator, for example ConnectionStrings__Default. Hosting platforms such as Azure App Service, AWS, Heroku-style platforms, Docker and Kubernetes all let you configure them without touching the code. Environment variables sit near the top of the precedence list, so they override the files.

They are not perfect: a process listing, a crash dump or a careless Console.WriteLine(Environment.GetEnvironmentVariables()) can reveal them, and every child process inherits them.

Key vaults and secret managers

Larger systems keep secrets in a dedicated service (Azure Key Vault, AWS Secrets Manager, HashiCorp Vault, Google Secret Manager). The app authenticates with a managed identity rather than a password, which solves the "secret to get the secrets" problem, and the vault provides access control, auditing, rotation and versioning. Integration is a configuration provider added to the builder. For example, with the Azure packages (read-only, these are NuGet packages we cannot install here):

C#
builder.Configuration.AddAzureKeyVault(
    new Uri("https://my-vault.vault.azure.net/"),
    new DefaultAzureCredential());

After that, ConnectionStrings--Default in the vault appears as the configuration key ConnectionStrings:Default, exactly as if it had come from a file.

Mounted secret files

Docker and Kubernetes can mount each secret as a small file in a folder. The built-in key-per-file provider reads such a folder: the file name is the key and the file content is the value. A file named ConnectionStrings__Default becomes the key ConnectionStrings:Default. This pattern keeps secrets out of environment listings.

Layers in action (a stand-in)

We cannot use a real user profile, vault or mounted volume, but we can reproduce the structure: a base file with an empty placeholder, a secrets store outside the content root that is added only in Development, and a mounted-files folder that is added in Production. Both secret stores end up in the same IConfiguration key.

C# Secrets layered over the base settings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The base file contains only an empty placeholder, so the repository holds nothing sensitive. Development gets its value from the profile file, Production from the mounted file, and the code that calls GetConnectionString("Default") is identical in both cases. The Redact helper shows the habit that goes with this: never print or log a full secret. Mask it, or log only that it exists.

In the real framework, the user secrets provider is AddUserSecrets<T>() and it is wired by WebApplication.CreateBuilder in Development without any code from you. The stand-in above only imitates its effect: a file outside the project that overrides the base settings.

Secret hygiene

  • Never commit secrets, even to private repositories. If one slips in, treat it as leaked: rotate it, then clean the history.
  • Use different secrets per environment. A developer's laptop should never hold production credentials.
  • Rotate regularly and design for it: read secrets through IOptionsMonitor or fetch them when needed rather than caching forever.
  • Log carefully. Redact connection strings, tokens and authorization headers. Be wary of logging whole configuration trees or request headers.
  • Grant least privilege. The application's database account should do only what the application needs.
  • Prefer identities over passwords where the platform offers them (managed identity, IAM roles, workload identity).
  • Keep secrets out of client-side code. Anything sent to a browser or a mobile app is public. Signing keys and API secrets belong on the server.
  • Remember that appsettings.json is copied to the output folder and published with the app. Placeholders only.

Configuration is now complete: layered, typed, validated and safe to deploy. The next lesson turns to the other half of day-to-day operations, logging and diagnostics.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which environment does an ASP.NET Core app use when ASPNETCORE_ENVIRONMENT is not set?

    The default is Production, so a forgotten setting on a server gives the safe behavior, without detailed error pages or development-only features.
  2. 2. Where does the default WebApplication.CreateBuilder load user secrets?

    User secrets are a development convenience. They are added automatically only in the Development environment and are not meant for production.
  3. 3. How is the key Db:Password normally written as an environment variable?

    Double underscores stand in for the colon, because colons are not allowed in environment variable names in every shell.
  4. 4. What is true about user secrets?

    The secrets.json file lives in the user profile and is linked to the project by an id. It keeps secrets out of Git, but it is plain text and only for development.
  5. 5. Why is a key vault with a managed identity often preferred in production?

    A managed identity authenticates the app without a stored credential, and the vault adds auditing, versioning and rotation.

Summary

  • The environment is a name from ASPNETCORE_ENVIRONMENT; it defaults to Production, and Development, Staging and Production have built-in helpers.
  • The name selects appsettings.{Environment}.json, turns on development-only features such as user secrets, the developer exception page and scope validation, and lets your wiring code branch.
  • Keep environment differences in configuration, not in scattered if statements.
  • Secrets must never be committed. Use user secrets in development, and environment variables, mounted files or a key vault in production.
  • Every store feeds the same IConfiguration, so code reads secrets exactly like other settings.
  • Redact secrets in logs, use separate secrets per environment, and prefer identity-based access over passwords.

Next: Logging and Diagnostics