In .NET, read secrets through IConfiguration, which merges appsettings.json, environment variables and, in development, the Secret Manager. Store real values with dotnet user-secrets locally and as environment variables or a vault in production. Never commit them to appsettings.json.
Read the key from the environment
var builder = WebApplication.CreateBuilder(args);
// Reads Stripe:SecretKey from user-secrets (dev) or the
// Stripe__SecretKey environment variable (production).
var apiKey = builder.Configuration["Stripe:SecretKey"]
?? throw new InvalidOperationException("Stripe:SecretKey is not set");Local development
Run dotnet user-secrets init in the project, then dotnet user-secrets set "Stripe:SecretKey" "<value>". The values are stored in your user profile, outside the repository, and loaded automatically in the Development environment. Microsoft notes the Secret Manager stores values unencrypted in the profile folder, so it is for development only, not a vault.
Production
In production, use environment variables (Stripe__SecretKey, with double underscores for the colon), or a service such as Azure Key Vault added as a configuration provider, ideally authenticated with a managed identity so no credential is needed to fetch the secrets. Avoid storing production secrets in appsettings.Production.json.
Mistakes to avoid
- Committing
appsettings.jsonorappsettings.Development.jsonwith literal secrets or connection strings that include passwords. - Assuming user secrets are encrypted or available in production; they are a development-time store only.
- Logging
IConfigurationcontents or connection strings, which can expose credentials. - Forgetting that the
:in a key is written__in environment variable names on Linux and in containers.
When an AI agent works on your .NET project
Coding agents run inside your project folder, so they can read the same .env file your app reads. BotPassword injects keys at run time instead: the agent calls the run_with intent through the MCP server and the process gets the variables it needs while the agent sees only redacted output. Planned: bpw run, a CLI form of the same.
Frequently asked questions
How do I store secrets in a .NET project?
Use the Secret Manager (dotnet user-secrets) in development and environment variables or Azure Key Vault in production, read through IConfiguration.
Are .NET user secrets encrypted?
No. They are stored as plain text in your user profile, outside the project folder. They keep secrets out of source control but are not a secure vault.
Should I keep API keys in a .env file for .NET?
A .env file that is git-ignored is fine for local development, but every process and every AI coding agent running in that folder can read it. Load secrets into the environment at run time from a password manager or secrets manager instead, so no plaintext file sits in the project.