7.3 — Environment Variables, Command-Line Args, User Secrets¶
← Roadmap · Section: 7. Configuration and Options Prev: 7.2 appsettings.json · Next: 7.4 Secret providers
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
The three providers that sit above the JSON files, and the two that carry secrets.
- User Secrets — local development secrets, stored outside the project folder so they cannot be committed. Development only.
- Environment variables — how deployment platforms supply settings. Nested keys use double underscores.
- Command-line arguments — highest precedence of all. For one-off overrides.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| User Secrets | a development feature | Settings stored in your user profile, outside the project, so git cannot see them. |
UserSecretsId |
a GUID in the .csproj |
Links the project to its secrets file. |
secrets.json |
a file | Where User Secrets live, under your user profile directory. |
dotnet user-secrets |
a CLI command | Sets, lists and removes secrets. |
| Environment variable | an OS-level setting | A name/value pair the process reads at startup. |
__ |
an escape sequence | Double underscore in a variable name becomes : in the key path. |
AddEnvironmentVariables(prefix) |
a method | Loads only variables with a given prefix, stripping it. |
| Command-line argument | a startup argument | --Key=Value or --Key Value. Highest precedence. |
| Switch mapping | an alias | Maps a short argument like -e to a full key path. |
args |
the Main parameter |
Must be passed to CreateBuilder(args) or command-line config does not work. |
The concept¶
Why secrets cannot live in JSON¶
appsettings.json is committed to source control
(7.2). Anything in it is:
- In your git history permanently, even if you delete it later
- Visible to everyone with repository access
- Picked up by automated secret scanners, which is how leaked keys get found
- Present in every clone, every fork, and every CI checkout
So a real API key in appsettings.json is effectively published.
But you still need those values to run the application locally. That is the problem User Secrets solves: settings that behave like configuration but live outside the project folder, where git cannot reach them.
A picture: your house keys versus the address on your business card. The address is fine to print and hand out. The keys stay in your pocket, and no amount of "I will remember to take them off the card later" makes printing them acceptable.
The three, and where each fits¶
| Provider | Used for | Available in |
|---|---|---|
| User Secrets | Local secrets during development | Development only |
| Environment variables | Deployment settings and secrets | Everywhere |
| Command-line arguments | Temporary overrides while debugging | Everywhere |
Precedence runs upward — command line beats environment variables, which beat User Secrets, which beat the JSON files (7.1).
How it works¶
The simple version — User Secrets¶
# Once per project — adds a UserSecretsId to the .csproj
dotnet user-secrets init
# Set values. Note the COLON, not double underscore, in the CLI.
dotnet user-secrets set "ConnectionStrings:Default" "Server=localhost;Database=Dev;..."
dotnet user-secrets set "Payments:ApiKey" "sk_test_abc123"
dotnet user-secrets list
dotnet user-secrets remove "Payments:ApiKey"
dotnet user-secrets clear
init adds one line to the project file:
<PropertyGroup>
<UserSecretsId>a1b2c3d4-e5f6-7890-abcd-ef1234567890</UserSecretsId>
</PropertyGroup>
That GUID is the only link. The values themselves live at:
Windows: %APPDATA%\Microsoft\UserSecrets\<UserSecretsId>\secrets.json
Linux: ~/.microsoft/usersecrets/<UserSecretsId>/secrets.json
macOS: ~/.microsoft/usersecrets/<UserSecretsId>/secrets.json
Outside the project folder, so git add . cannot pick them up. That is the entire mechanism —
and it is the reason to prefer them over a gitignored file, which one careless git add -f can
still commit.
Reading them needs no code — they are already in the provider chain:
⚠️ User Secrets load in Development only. In any other environment the provider is not added, so the value is simply absent. That is deliberate — they are not a deployment mechanism.
⚠️ And they are not encrypted. They are plain JSON in your profile directory. The protection is that they are outside source control, not that they are secure at rest. Anyone with access to your machine can read them.
Environment variables¶
# Linux / macOS
export ConnectionStrings__Default="Server=prod;Database=App;..."
export Payments__ApiKey="sk_live_..."
# Windows PowerShell
$env:ConnectionStrings__Default = "Server=prod;..."
⚠️ Double underscore for nesting. ConnectionStrings__Default maps to the key
ConnectionStrings:Default. A single underscore does not work, and there is no error — the
value is silently absent and the app falls back to whatever the JSON said.
This is one of the most common deployment mistakes in ASP.NET Core.
In the places you actually set them:
# Kubernetes — plain settings inline, secrets by reference
env:
- name: ASPNETCORE_ENVIRONMENT
value: "Production"
- name: ConnectionStrings__Default
valueFrom:
secretKeyRef:
name: app-secrets
key: connection-string
Using a Kubernetes secret reference rather than a literal is the point. The manifest goes in source control; the secret does not.
Prefixed variables avoid collisions on shared machines:
The prefix is stripped, so your keys stay clean.
Command-line arguments¶
dotnet run --Logging:LogLevel:Default=Debug
dotnet run --ConnectionStrings:Default="Server=test;..."
dotnet MyApp.dll --Orders:MaxItems=50
Note these use colons, not double underscores — the shell is not the constraint here.
⚠️ args must be passed through, or none of this works:
var builder = WebApplication.CreateBuilder(args); // ✓
var builder = WebApplication.CreateBuilder(); // ✗ command-line config silently dead
The second compiles and runs. Command-line overrides just do nothing.
Switch mappings give you short aliases:
var switchMappings = new Dictionary<string, string>
{
["-e"] = "ASPNETCORE_ENVIRONMENT",
["--conn"] = "ConnectionStrings:Default"
};
builder.Configuration.AddCommandLine(args, switchMappings);
The deeper detail — which to use where¶
Local development
└── User Secrets ← real local secrets, outside source control
CI pipeline
└── Environment variables ← from the CI system's secret store
Container / Kubernetes
└── Environment variables ← from a Kubernetes Secret or the platform's store
Azure App Service
└── Application settings ← surface as environment variables automatically
Production, ideally
└── Key Vault ← see 7.4
⚠️ Environment variables are visible to the whole process and its children. Anything that can
read /proc/self/environ, or crash and dump the environment, sees them. That includes the
developer exception page, which renders every environment variable into the browser
(4.7).
So they are better than committing secrets, and not as good as a dedicated secret store. For anything genuinely sensitive in production, Key Vault or its equivalent is the right answer — 7.4.
Code¶
The realistic split for one application:
// appsettings.json — committed. Structure and non-secret defaults.
{
"Payments": {
"BaseUrl": "https://api.stripe.com",
"TimeoutSeconds": 30,
"MaxRetries": 3
// ApiKey deliberately absent
}
}
# Local development — User Secrets
dotnet user-secrets set "Payments:ApiKey" "sk_test_abc123"
dotnet user-secrets set "ConnectionStrings:Default" "Server=(localdb)\\mssqllocaldb;Database=Dev;..."
# Production — Kubernetes, secret by reference
env:
- name: Payments__ApiKey
valueFrom:
secretKeyRef: { name: app-secrets, key: stripe-api-key }
- name: ConnectionStrings__Default
valueFrom:
secretKeyRef: { name: app-secrets, key: sql-connection }
// The application code is identical in both — it just reads configuration
builder.Services.Configure<PaymentOptions>(builder.Configuration.GetSection("Payments"));
The application never knows where the value came from. That is the point of the provider model — one build, and the source of each setting is a deployment concern.
Failing fast on a missing secret¶
var apiKey = builder.Configuration["Payments:ApiKey"];
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new InvalidOperationException(
"Payments:ApiKey is not configured. Set it via User Secrets locally " +
"or as the Payments__ApiKey environment variable in deployment.");
}
That message is worth writing properly. A missing secret otherwise surfaces as a 401 from the
payment provider hours later, and the error tells whoever hits it exactly what to do. Better
still, use options validation with ValidateOnStart —
7.8.
Interview questions¶
Q: Where do you put secrets during local development?
User Secrets. You run dotnet user-secrets init, which adds a UserSecretsId GUID to the
project file, and then set values with the CLI. The values are stored in a secrets.json under
your user profile directory — outside the project folder entirely, so git cannot pick them up
even accidentally. They are read automatically as a configuration provider in Development, so
the application code is unchanged. Worth knowing they are not encrypted; the protection is that
they are outside source control, not that they are secure at rest.
Q: How do you set a nested configuration key as an environment variable?
With double underscores. Configuration keys are colon-separated, like ConnectionStrings:Default,
but environment variable names cannot reliably contain colons across platforms, so the convention
is ConnectionStrings__Default. Using a single underscore is a very common deployment mistake
and produces no error — the variable is simply not recognised as that key, so the application
silently falls back to whatever the JSON file said, which usually means pointing at the wrong
database.
Q: What is the precedence between these providers?
Command-line arguments beat environment variables, which beat User Secrets, which beat the
environment-specific JSON file, which beats the base JSON file. That ordering is deliberate: the
files supply defaults that are safe to commit, User Secrets supply local secrets, environment
variables supply deployment values, and the command line lets you override anything temporarily.
One thing to watch is that command-line configuration only works if args is passed to
CreateBuilder — omitting it compiles fine and silently disables that provider.
Q: Are environment variables a good place for production secrets?
They are much better than committing them, and not as good as a dedicated secret store. The problem is exposure: environment variables are visible to the whole process and any child process, they appear in crash dumps, and the developer exception page renders every one of them into the browser — so a misconfigured environment turns them into an information disclosure. For production I would use Key Vault or the platform's secret manager, with environment variables used to supply the identity that reaches it rather than the secrets themselves.
Traps ⚠️¶
- Single underscore instead of double in an environment variable name silently does nothing.
- User Secrets are Development-only. They are not a deployment mechanism.
- User Secrets are not encrypted — just outside source control.
CreateBuilder()withoutargssilently disables command-line configuration.- Environment variables are visible to the whole process, appear in dumps, and are rendered by the developer exception page.
- Command-line args use colons; environment variables use double underscores. Mixing them up is common.
dotnet user-secretsmust run from the project directory containing the.csproj, or it cannot find theUserSecretsId.- Deleting a secret from a JSON file does not remove it from git history. Once committed, rotate the credential.
Related¶
- 7.1 The configuration system — precedence in full
- 7.2 appsettings.json — what belongs in the committed files
- 7.4 Secret providers — Key Vault for production
- 7.8 Options validation — failing fast on a missing secret
- 4.7 Environments — why the exception page is a risk
- 4.8 launchSettings.json — why secrets do not go there
- 17.7 Secrets management — the security view
- 24.3 Dockerfile — setting variables in containers