Environment is Determined in .NET Core

 

The ASPNETCORE_ENVIRONMENT environment variable decides which environment is active.

 

Common Environment Names we can set with above vairables are

  • Development
  • Staging
  • Production (default if none is specified)

 

 

Where to Set the Environment?

launchSettings.json (when running via Visual Studio or dotnet run) - locate this file at: Properties/launchSettings.json

{
 "$schema": "http://json.schemastore.org/launchsettings.json",
 "iisSettings": {
   "windowsAuthentication": false,
   "anonymousAuthentication": true,
   "iisExpress": {
     "applicationUrl": "http://localhost:55929",
     "sslPort": 44390
   }
 },
 "profiles": {
   "http": {
     "commandName": "Project",
     "dotnetRunMessages": true,
     "launchBrowser": true,
     "launchUrl": "swagger",
     "applicationUrl": "http://localhost:5173",
     "environmentVariables": {
       "ASPNETCORE_ENVIRONMENT": "Development"
     }
   },
   "https": {
     "commandName": "Project",
     "dotnetRunMessages": true,
     "launchBrowser": true,
     "launchUrl": "swagger",
     "applicationUrl": "https://localhost:7021;http://localhost:5173",
     "environmentVariables": {
       "ASPNETCORE_ENVIRONMENT": "Development"
     }
   },
   "IIS Express": {
     "commandName": "IISExpress",
     "launchBrowser": true,
     "launchUrl": "swagger",
     "environmentVariables": {
       "ASPNETCORE_ENVIRONMENT": "Development"
     }
   }
 }
}

 

 

Fetch Active Environment in Code

 

 

Which appsettings file will be loaded

Your environment determines which appsettings file is loaded:

  • appsettings.json
    • Always loaded
  • appsettings.Development.json   
    • only if ASPNETCORE_ENVIRONMENT=Development
  • appsettings.Production.json   
    • if ASPNETCORE_ENVIRONMENT=Production
       

These files are combined with overrides by.NET in accordance with the active environment. 

 

 

In Short

  • launchSettings.json
    • Sets ASPNETCORE_ENVIRONMENT for local development
  • appsettings.{env}.json
    • Used for environment-specific configuration
  • launch.json
    • (VS Code only) Set env variable for debugging
  • ASPNETCORE_ENVIRONMENT
    • Primary switch for active environment

 


Related Question