skip to content

In ASP.NET Core, why does a key stored with dotnet user-secrets load in Development but read null in Staging, and how do you load it elsewhere?

level: middleimportance: should knowfreq 50%

answer

  1. added only when IsDevelopment()
  2. UserSecretsIdAttribute on the app assembly
  3. AddUserSecrets<Program>() by hand
  4. optional true, reloadOnChange false
  5. optional false: InvalidOperationException

basics

~10 s

WebApplication.CreateBuilder adds the user-secrets source only when the environment is Development, finding the store through the app assembly's UserSecretsIdAttribute. In Staging nothing reads secrets.json; call builder.Configuration.AddUserSecrets<Program>() where a non-Development run really needs it.

solid answer

~40 s

The default builder checks `env.IsDevelopment()`; only then does it load the assembly named by `ApplicationName`, read its `UserSecretsIdAttribute` and add `secrets.json` as an optional JSON source. Under Staging, Production or a custom environment name the source is never added, so `builder.Configuration["Maps:ApiKey"]` is `null`. It also skips silently when the attribute is missing, for example with no `UserSecretsId` or with `GenerateUserSecretsAttribute` set to `false`. To use the store in another environment on a developer machine, call `builder.Configuration.AddUserSecrets<Program>()`. That overload is optional and does not reload unless you pass `reloadOnChange: true`; with `optional: false`, a missing attribute throws `InvalidOperationException`. A console app built on `ConfigurationBuilder` adds the `Microsoft.Extensions.Configuration.UserSecrets` package and calls it too. A server must not rely on it at all.

code

csharp · 8 lines
csharp
// A console tool has no default sources: add them yourself.
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true)
    .AddUserSecrets<Program>(optional: false)
    .Build();

string? mapsKey = config["Maps:ApiKey"];
Console.WriteLine(mapsKey is null ? "maps key missing" : "maps key loaded");

go deeper

for a junior

Remember that user secrets are read only when the environment is Development, so a stored value disappears under Staging or Production.

for a middle

Explain the IsDevelopment check, the UserSecretsIdAttribute lookup, the silent skips, and the defaults of AddUserSecrets<Program>().

for a senior

Diagnose a null secret quickly: environment name, missing attribute, changed ApplicationName; load the store explicitly only behind an environment check.

for a principal

Keep developer-only sources out of anything a server could run, so a production deployment can never quietly depend on a file on someone's laptop.

## How the default builder adds user secrets `WebApplication.CreateBuilder(args)` (and `Host.CreateApplicationBuilder` for a worker) runs the same default app-configuration step. For user secrets it does this: 1. Check `env.IsDevelopment()`, a case-insensitive comparison of the environment name with `Development`. 2. Load the assembly named by `env.ApplicationName`, normally the app's own project. 3. Call `AddUserSecrets(assembly, optional: true, reloadOnChange: ...)`, which reads `UserSecretsIdAttribute` and adds `secrets.json` from the profile path as a JSON source. The reload flag follows the host setting `hostBuilder:reloadConfigOnChange`, which defaults to `true`, so in Development an edit to `secrets.json` is picked up while the app runs. ## Why Staging reads null | Environment name | User-secrets source added by default? | `Maps:ApiKey` when it lives only in the store | |---|---|---| | `Development` | Yes | The stored value | | `Staging` | No | `null` | | `Production` | No | `null` | | `Local` (custom) | No | `null` | The file is still on the laptop; nothing reads it. That is deliberate: Secret Manager is a development convenience, and a deployed app must get its keys from the platform or a vault. ## Silent skips, even in Development The default path never fails startup. It quietly adds nothing when: - the project has no `UserSecretsId`, so the build emits no attribute; - `GenerateUserSecretsAttribute` is `false`, or `GenerateAssemblyInfo` is `false` so assembly attributes are not generated (add `[assembly: UserSecretsId("...")]` yourself); - `ApplicationName` was changed to a name that is not a loadable assembly; the builder catches the `FileNotFoundException` and moves on; - the environment name is misspelt, for example `Developement`. When a stored key reads `null` in Development, check these before suspecting the store. ## Loading the store explicitly | Call | Optional | Reload | Notes | |---|---|---|---| | `AddUserSecrets<Program>()` | `true` | `false` | Uses the attribute on `Program`'s assembly | | `AddUserSecrets<Program>(optional: false)` | `false` | `false` | Throws `InvalidOperationException` naming the assembly when the attribute is missing | | `AddUserSecrets<Program>(true, reloadOnChange: true)` | `true` | `true` | Watches `secrets.json` | | `AddUserSecrets("<id>")` | `true` | `false` | Uses an id string directly, with no attribute | A typical case is a laptop profile with its own environment name: ```csharp var builder = WebApplication.CreateBuilder(args); if (builder.Environment.IsEnvironment("Local")) { builder.Configuration.AddUserSecrets<Program>(); } ``` A source added after `CreateBuilder` goes to the end of the source list, so these secrets now outrank environment variables and command-line arguments as well. Wrapping the call in an environment check keeps that from reaching a server. ## Projects without the web defaults - **Worker services** use `Host.CreateApplicationBuilder`, which behaves like the web builder: user secrets in Development only. - **Console tools** that build `new ConfigurationBuilder()` get no defaults. They need the `Microsoft.Extensions.Configuration.UserSecrets` package, a `UserSecretsId`, and an explicit `AddUserSecrets<Program>()`. - **Web projects** already have the provider through the ASP.NET Core shared framework; no package is needed. ## Interview checklist - The default source is added only when the environment is Development. - Missing ids and attributes are skipped silently. - `AddUserSecrets<Program>()` loads the store anywhere; know its optional and reload defaults. - Never make a server depend on the store.

  • After someone sets GenerateAssemblyInfo to false, the stored maps key reads null even in Development. Why?
    The user-secrets targets add the `UserSecretsIdAttribute` as a generated assembly attribute. With assembly-info generation off, the attribute is never emitted, the default builder finds no id and skips the source without an error. Add `[assembly: UserSecretsId("<id>")]` to a source file, or turn generation back on.
  • Does an edit to secrets.json reach a running app?
    Through the default Development source, yes: it is registered with `reloadOnChange` taken from `hostBuilder:reloadConfigOnChange`, which defaults to `true`, so `IConfiguration` reads see the edit. A source you add yourself with `AddUserSecrets<Program>()` does not reload unless you pass `reloadOnChange: true`.
  • Is calling AddUserSecrets<Program>() unconditionally harmful in production?
    It usually loads nothing, because the overload is optional and the server has no `secrets.json` for that id. It is still misleading: a reader assumes the store supplies production values, and because the source sits last it would override every other source on any machine that happens to have the file. Gate it on an environment check.

  • User secrets load in every environment as long as secrets.json exists on the machine.
  • The default builder throws at startup when the project has no UserSecretsId.
  • AddUserSecrets<Program>() watches secrets.json for changes by default.
  • A console app built with ConfigurationBuilder picks up user secrets automatically.
  • Running the app as Staging on a laptop still reads secrets.json because the file is local.