Typical Runtime Error (.NET / ASP.NET Core .env Failure)
When syntax errors, unquoted special characters, missing keys, or public-prefix secret leaks slip into a .NET / ASP.NET Core .env file, your runtime or audit pipeline surfaces an error like the output below:
System.InvalidOperationException: Connection string "DefaultConnection" not found — Linux environment rejected single-colon "ConnectionStrings:DefaultConnection" key name.
How .NET / ASP.NET Core Loads .env Files, Precedence & Security Boundaries
ASP.NET Core's configuration system maps hierarchical JSON sections from appsettings.json cleanly onto OS environment variables; but Windows and Linux follow different delimiter rules. While Windows accepts single colons (ConnectionStrings:DefaultConnection), POSIX Linux shells, Docker Compose, and Kubernetes forbid colons in environment variable names and require double underscores (__) instead (ConnectionStrings__DefaultConnection).
Double underscores also support array indexing directly from .env files: Cors__AllowedOrigins__0=https://app.example.com and Cors__AllowedOrigins__1=https://admin.example.com populate builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() cleanly without editing appsettings.Production.json inside immutable Docker images.
Unlike Node.js or Laravel, ASP.NET Core does NOT read a .env file automatically during local dotnet run unless you load it via Docker Compose env_file:, launchSettings.json, or a library like DotNetEnv. Furthermore, when running .env files through Docker Compose or Linux systemd EnvironmentFile=, unquoted # characters in Jwt__SigningKey or spaces around = silently corrupt secrets before Kestrel ever boots.
This browser-only validator checks your ASP.NET Core .env files for unquoted # truncation, spaces around =, duplicate overrides, and missing production template keys; producing a clean Auto-Fixed .env and a sanitized .env.example safe for version control.
Always verify your active configuration precedence in staging: ASP.NET Core overlays Environment Variables on top of appsettings.{Environment}.json on top of appsettings.json, so keeping appsettings.Production.json free of real secrets and injecting ConnectionStrings__* at runtime keeps your .NET deployments compliant and portable.
Running ASP.NET Core 8 and 9 cleanly on Linux and Docker requires translating hierarchical appsettings.json sections into POSIX-safe double-underscore (__) environment keys while keeping production secrets completely outside appsettings.Production.json. Validate ConnectionStrings__*, Jwt__*, and Cors__AllowedOrigins__* keys with this browser-only linter before updating systemd EnvironmentFile= units or Docker Compose stacks, and enable Options pattern ValidateOnStart() so any typo or missing secret surfaces immediately during container boot.
Step-by-Step .NET / ASP.NET Core .env Configuration & Hardening Guide
Apply these four concrete safeguards to eliminate silent dotenv truncation, prevent secret leaks, and keep local and production environments synchronized.
1Map Nested appsettings.json Keys Using Double Underscores (__)
.env (Docker / Linux systemd)Replace every JSON colon (:) with a double underscore (__) and wrap any connection string or signing key containing # or semicolons in double quotes.
.env (Docker / Linux systemd)dotenvASPNETCORE_ENVIRONMENT=Production ASPNETCORE_HTTP_PORTS=8080 ConnectionStrings__DefaultConnection="Host=postgres;Port=5432;Database=app_db;Username=app;Password=my#secret" ConnectionStrings__Redis="redis:6379,abortConnect=false" Jwt__Issuer="https://api.example.com" Jwt__SigningKey="replace_with_256_bit_random_secret" Cors__AllowedOrigins__0="https://app.example.com"2Bind and Validate Strongly Typed Options on Startup in Program.cs
Program.csUse ValidateDataAnnotations().ValidateOnStart() so ASP.NET Core fails fast at boot if a double-underscore environment variable is misspelled or missing.
Program.cscsharpbuilder.Services.AddOptions<JwtOptions>() .Bind(builder.Configuration.GetSection("Jwt")) .ValidateDataAnnotations() .ValidateOnStart();3Load .env Cleanly Under Linux systemd Using EnvironmentFile=
/etc/systemd/system/kestrel-api.serviceStore production secrets in a chmod 600 file owned by root/www-data and reference it via EnvironmentFile= in your systemd unit.
/etc/systemd/system/kestrel-api.serviceini[Service] EnvironmentFile=/etc/kestrel-api/.env ExecStart=/usr/bin/dotnet /var/www/dotnet-api/Api.dll4Audit Loaded Configuration Providers Safely in Development
terminalVerify Docker Compose passed your double-underscore variables cleanly into the running .NET container.
terminalbashdocker compose exec api printenv | grep -E "ASPNETCORE|ConnectionStrings|Cors"
Common .NET / ASP.NET Core .env Pitfalls
Check these three framework-specific traps before deploying updated environment variables to staging or production.
Using Single Underscores (_) Instead of Double Underscores (__)
Writing ConnectionStrings_DefaultConnection (single underscore) fails to bind to builder.Configuration.GetConnectionString("DefaultConnection"). Always use double underscores (__) to represent JSON hierarchy levels.
Leaving Semicolons Unquoted When Sourcing .env in Bash
ADO.NET / Npgsql connection strings contain semicolons (Host=postgres;Port=5432;..). If you run source .env in Bash without double-quoting the connection string, Bash treats every semicolon as a command separator.
Expecting dotnet run to Auto-Load a .env File
ASP.NET Core uses Properties/launchSettings.json and dotnet user-secrets locally; not .env. Use dotnet user-secrets locally and inject .env via Docker Compose env_file: or systemd EnvironmentFile= in Linux production.
Pair Your Validated .env With Webhook HMAC, Docker Compose & CORS Tools
Now that your environment variables are syntax-clean and leak-free, verify webhook raw-body HMAC signatures, container healthchecks, and browser cross-origin rules:
Verify Stripe, GitHub, and Shopify HMAC-SHA256 webhooks in ASP.NET Core 8/9 using EnableBuffering(), StreamReader, and FixedTimeEquals in C#.
Generate a Docker Compose config for ASP.NET Core 8/9 Web API, PostgreSQL 16 (Npgsql), and Redis distributed cache with pg_isready and redis-cli healthchecks.
Fix CORS errors between ASP.NET Core 8/9 Web API and Angular CLI on port 4200. Verify UseCors middleware ordering, AllowCredentials, and HTTPS redirects.
Frequently Asked Questions
- Why does ASP.NET Core use double underscores (__) for environment variables?
- ASP.NET Core uses ":" internally to separate nested JSON sections, but ":" is invalid in POSIX shell variable names on Linux. The .NET EnvironmentVariablesConfigurationProvider automatically translates "__" into ":" at startup.
- How do I override a JSON array in appsettings.json using a .env file?
- Append zero-based numeric indices separated by double underscores: Cors__AllowedOrigins__0=https://app.example.com and Cors__AllowedOrigins__1=https://admin.example.com.
- Are ASP.NET Core environment variable keys case-sensitive on Linux?
- ASP.NET Core's IConfiguration lookup is case-insensitive, so JWT__SIGNINGKEY and Jwt__SigningKey both bind to Jwt:SigningKey; though matching exact PascalCase makes Docker debugging much clearer.
- Should I use dotnet user-secrets or .env files for local .NET development?
- Use dotnet user-secrets for standalone local dotnet run workflows (stored outside your Git repo) and Docker Compose .env files (with .env gitignored) when running full multi-container stacks.
Related Framework .env Guides
Browse all 10 .env guides →Docker Compose .env Validator & $$ Dollar Escaping Checker
Fix Docker Compose .env substitution bugs and broken bcrypt hashes. Detect unescaped $ characters, spaces around =, and .env vs env_file differences locally.
FastAPI & Pydantic Settings .env Validator (Fix ValidationError & Delimiters)
Validate Python FastAPI and pydantic-settings .env files in your browser. Fix pydantic_core.ValidationError, nested __ delimiters, unquoted #, and DEBUG leaks.
Laravel .env Validator & APP_KEY Checker (Fix Unquoted # & Config Errors)
Validate Laravel 11/12 .env files locally in your browser. Fix InvalidFileException, unquoted # in DB_PASSWORD, invalid base64 APP_KEY, and config:cache traps.
GitHub Actions & POSIX Shell .env Validator (Fix source .env & CI Leaks)
Validate CI/CD and GitHub Actions .env files locally in your browser. Fix POSIX source .env syntax errors, unquoted spaces, and accidental secret exposure.