skip to content

In ASP.NET Core, how does AddKeyPerFile turn a directory of mounted secret files, such as /run/secrets, into configuration keys?

level: middleimportance: nice to knowfreq 22%

answer

  1. one file, one key
  2. file name is the key, content the value
  3. __ in the name becomes :
  4. ignore. prefix and dotfiles skipped
  5. optional false: DirectoryNotFoundException

basics

~20 s

AddKeyPerFile reads every file in a directory: the file name, with __ turned into :, becomes the key and the file content becomes the value after one trailing newline is trimmed. A file named Maps__ApiKey therefore supplies Maps:ApiKey.

solid answer

~40 s

`builder.Configuration.AddKeyPerFile("/run/secrets", optional: true)` adds a `KeyPerFileConfigurationProvider`, which ships in the ASP.NET Core shared framework. It lists the files directly in that folder (subfolders are skipped), uses each file name as the key, replacing the `SectionDelimiter` `__` with `:`, and the content as the value, trimming one trailing `Environment.NewLine`. Files whose names start with `ignore.` are skipped through `IgnorePrefix`, and the physical file provider also hides dot-prefixed files. Defaults matter: the one-argument overload is not optional, so a missing directory throws `DirectoryNotFoundException`, the path must be absolute, and `reloadOnChange` is `false`. This is how secrets mounted as files by a container orchestrator reach `builder.Configuration["Maps:ApiKey"]`.

code

bash · 5 lines
bash
mkdir -p /run/secrets
printf '%s' 'mk_live_123' > /run/secrets/Maps__ApiKey
printf '%s' 'tok_live_456' > /run/secrets/Sms__AuthToken
echo 'mounted by the platform' > /run/secrets/ignore.readme
ls /run/secrets

go deeper

for a junior

Know that AddKeyPerFile reads a folder where each file is one setting: the name is the key and the content is the value.

for a middle

Explain the __ to : mapping, the single-newline trim, the ignore. prefix, and the optional and reloadOnChange defaults.

for a senior

Harden it: make the mount optional only with explicit checks, write files without stray line endings, and enable reload where secrets rotate.

for a principal

Decide which secrets arrive as mounted files versus a vault provider, so each app has one obvious place to look and rotation works the same way everywhere.

## What the provider does Container platforms often deliver secrets as **one file per secret** in a mounted folder. The **key-per-file provider** reads such a folder into configuration: 1. Open the directory through a `PhysicalFileProvider`. 2. For each file directly in it, skip it if it is a directory or matches the ignore rule. 3. Use the **file name** as the key, replacing `__` with `:`. 4. Use the **file content** as the value, trimming **one** trailing `Environment.NewLine`. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Configuration.AddKeyPerFile("/run/secrets", optional: true); string? mapsKey = builder.Configuration["Maps:ApiKey"]; ``` The provider lives in `Microsoft.Extensions.Configuration.KeyPerFile`, part of the ASP.NET Core shared framework, so a web project needs no extra package. ## Naming | File in `/run/secrets` | Configuration key | Loaded? | |---|---|---| | `Maps__ApiKey` | `Maps:ApiKey` | Yes | | `Sms__AuthToken` | `Sms:AuthToken` | Yes | | `Maps__ApiKey.txt` | `Maps:ApiKey.txt` | Yes, under the wrong key | | `ignore.readme` | none | No, matches `IgnorePrefix` | | `.hidden` | none | No, the file provider hides dot-prefixed files | | `nested/Token` | none | No, subdirectories are skipped | Keys compare case-insensitively like every other key, so `MAPS__APIKEY` also fills `Maps:ApiKey`. ## Defaults on `KeyPerFileConfigurationSource` | Property | Default | Meaning | |---|---|---| | `IgnorePrefix` | `"ignore."` | Files starting with it are skipped | | `IgnoreCondition` | uses `IgnorePrefix` | Replace it and the prefix rule is gone unless you keep it | | `SectionDelimiter` | `"__"` | Replaced by `:` in file names | | `Optional` | `false` via `AddKeyPerFile(path)` | A missing directory throws | | `ReloadOnChange` | `false` | Files are read once | | `ReloadDelay` | `250` ms | Wait after a change before re-reading | The three-argument overload `AddKeyPerFile(path, optional, reloadOnChange)` and the `Action<KeyPerFileConfigurationSource>` overload set these. ## Startup failures - **Missing directory, not optional:** `DirectoryNotFoundException` while the source is added. - **Relative path:** the physical file provider requires an absolute path and throws `ArgumentException` ("The path must be absolute.") whenever it is created: always for a required directory, and for an optional one when a folder with that relative name exists. - **Optional and missing:** the provider contributes no keys, which hides a forgotten mount; validate the keys you depend on. ## Newlines and whitespace Only one `Environment.NewLine` at the very end is removed. `echo key > Maps__ApiKey` writes `key` plus `\n`, which is trimmed on Linux. A file saved with Windows line endings keeps a stray `\r` on Linux, and a file with two trailing newlines keeps one: both produce an API key the maps service rejects. Write secret files with `printf '%s'` or without a final line ending. ## Placement and reload - Called after `CreateBuilder`, the provider is the last source, so a mounted file outranks environment variables and command-line arguments. - With `reloadOnChange: true` the provider watches the directory, waits `ReloadDelay`, re-reads every file and fires the reload token, so `IConfiguration` reads see a rotated file. - `GetDebugView()` names the key-per-file provider beside each key it supplied, which confirms the mount was found and read. ## Interview checklist - File name is the key with `__` as `:`; content is the value. - One trailing newline is trimmed, nothing more. - `ignore.` prefix, dotfiles and subfolders are skipped. - `AddKeyPerFile(path)` is not optional; reload is off by default.

  • The maps service rejects a key loaded with AddKeyPerFile on Linux, although the file looks right. What is a likely cause?
    A line ending the provider did not trim. It removes exactly one `Environment.NewLine`, which is `\n` on Linux, so a file saved with Windows line endings keeps a trailing `\r`, and a file ending in two newlines keeps one. Rewrite the file without a final line ending, for example with `printf '%s'`.
  • You set IgnoreCondition to skip files ending in .md, and now ignore.readme shows up as a key. Why?
    By default `IgnoreCondition` is a function that checks `IgnorePrefix`. Assigning your own condition replaces that function, so the `ignore.` rule is gone. Combine both checks in your condition if you still want the prefix honoured.
  • What happens when AddKeyPerFile("/run/secrets") runs and the folder is missing?
    The one-argument overload sets `optional` to `false` and creates a physical file provider for the path, which throws `DirectoryNotFoundException` while the source is added, so startup fails. Pass `optional: true` when the mount may be absent, and then check the required keys yourself.

  • AddKeyPerFile parses each file as JSON and merges the objects it finds.
  • The provider trims all surrounding whitespace from every file's content.
  • Subdirectories are read recursively and become nested sections.
  • AddKeyPerFile(path) silently ignores a directory that does not exist.
  • Mounted files are re-read automatically whenever they change.