The Problem
Your appsettings.json has a database password in plain text. Your teammate just pushed their local connection string to main. The staging API key is in a Slack thread from six months ago, and nobody remembers which .env.local file has the right values.
You need a single, secure system for managing secrets across every environment — one that encrypts sensitive values, integrates with .NET's configuration system, and never lets a plaintext secret touch your Git history.
Ingredients
Noundry.DotEnvX
vlatest
Environment variable management with encryption support
Noundry.DotEnvX.Tool
vlatest
CLI tool for managing .env files (ndotenvx)
.NET 10 SDK
v10.0
Target framework for the project
The core package handles everything. The CLI tool is optional but recommended for managing encrypted values.
Preparation
dotnet add package Noundry.DotEnvX
# Optional: Install the CLI globally
dotnet tool install --global Noundry.DotEnvX.Tool
2. Create your .env file
Create a .env file in your project root:
# Application settings
APP_NAME=MyApp
APP_ENV=development
# Database
DATABASE_URL=Host=localhost;Database=myapp;Username=postgres;Password=devpass123
# External services
STRIPE_API_KEY=sk_test_abc123
SENDGRID_API_KEY=SG.test-key-here
3. Update .gitignore
Add these entries to your .gitignore:
.env.keys
.env.local
.env.*.local
The Code
DotEnvX integrates directly into ASP.NET Core's configuration pipeline. Here's a complete setup from basic loading to encrypted secrets.
using Noundry.DotEnvX.Core;
using Noundry.DotEnvX.Core.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Load environment-specific .env files
// Later files override earlier ones
builder.Configuration.AddDotEnvX(options =>
{
options.Path = new[]
{
".env",
$".env.{builder.Environment.EnvironmentName.ToLower()}"
};
options.Overload = true;
});
// Register the DI service for injecting into your classes
builder.Services.AddDotEnvX();
// Now use configuration values anywhere
var dbUrl = builder.Configuration["DATABASE_URL"];
var app = builder.Build();
app.Run();
using Noundry.DotEnvX.Core.Extensions;
namespace MyApp.Services;
public class PaymentService
{
private readonly string _apiKey;
public PaymentService(IDotEnvService env)
{
// GetRequired throws KeyNotFoundException if missing
_apiKey = env.GetRequired("STRIPE_API_KEY");
}
public string GetEnvironment()
{
// Safe access patterns
return _env.GetOrDefault("APP_ENV", "production");
}
}
// Register in DI
// builder.Services.AddScoped<PaymentService>();
# Step 1: Generate an encryption keypair
ndotenvx keypair --save
# Creates .env.keys (NEVER commit this!)
# Adds public key comment to .env
# Step 2: Encrypt sensitive values
ndotenvx set DATABASE_PASSWORD=RealProdPassword123! --encrypt
ndotenvx set STRIPE_API_KEY=sk_live_real_key --encrypt
# Step 3: Verify encryption
ndotenvx get DATABASE_PASSWORD
# Output: RealProdPassword123! (auto-decrypted using .env.keys)
# Step 4: View raw .env to confirm encryption
cat .env | grep DATABASE_PASSWORD
# Output: DATABASE_PASSWORD="encrypted:BDb7t3QkTRp2..."
# The .env file is now safe to commit!
# Encrypted values auto-decrypt when .env.keys is present
# Create a vault for multi-environment deployment
# Vault files contain encrypted copies of entire .env files
# Step 1: Create environment-specific .env files
# .env.production, .env.staging already exist
# Step 2: Create the vault (encrypts everything)
ndotenvx ext vault --create
# Output: Created .env.vault with environments: production, staging
# Output: DOTENV_KEY_PRODUCTION=dotenv://:[email protected]/vault/.env.vault?environment=production
# Output: DOTENV_KEY_STAGING=dotenv://:[email protected]/vault/.env.vault?environment=staging
# Step 3: Store DOTENV_KEYs in CI/CD secrets (GitHub, Railway, etc.)
# Step 4: Commit .env.vault to Git (it's fully encrypted)
# In production, set DOTENV_KEY environment variable
# DotEnvX auto-detects and decrypts the vault
Plating
Your secrets management is now production-grade:
- Local development loads
.envand.env.localwith plaintext values for convenience - Encrypted values use ECIES (secp256k1 + AES-256-GCM) — the same curve as Bitcoin
- Vault files package entire environments into a single encrypted file safe for Git
- DI integration with
IDotEnvServiceprovidesGetRequired(),GetOrDefault(), andTryGet()patterns - Hot reload detects
.envfile changes and firesReloadedevents
The golden rule: .env.keys files never leave the developer's machine. DOTENV_KEYs go into your CI/CD secret store.
Next steps:
- Set up
ndotenvx rotatefor periodic key rotation - Use
ndotenvx validatein your CI pipeline to catch syntax errors - Combine with Noundry.Guardian to validate configuration values at startup
Was this recipe helpful?
Chef George
.NET Architect & Head Chef
25+ years crafting enterprise C# solutions. Creator of the Noundry platform. Passionate about clean architecture, cloud-agnostic deployments, and code that cooks.