Update for .NET Core 3.0+
-
You can use
CreateDefaultBuilderwhich will automatically build and pass a configuration object to your startup class:WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();public class Startup { public Startup(IConfiguration configuration) // automatically injected { Configuration = configuration; } public IConfiguration Configuration { get; } /* ... */ } -
CreateDefaultBuilderautomatically includes the appropriateappsettings.Environment.jsonfile so add a separate appsettings file for each environment:
-
Then set the
ASPNETCORE_ENVIRONMENTenvironment variable when running / debugging
How to set Environment Variables
Depending on your IDE, there are a couple places dotnet projects traditionally look for environment variables:
-
For Visual Studio go to Project > Properties > Debug > Environment Variables:

-
For Visual Studio Code, edit
.vscode/launch.json>env:
-
Using Launch Settings, edit
Properties/launchSettings.json>environmentVariables:
Which can also be selected from the Toolbar in Visual Studio

-
Using dotnet CLI, use the appropriate syntax for setting environment variables per your OS
Note: When an app is launched with dotnet run,
launchSettings.jsonis read if available, andenvironmentVariablessettings in launchSettings.json override environment variables.
How does Host.CreateDefaultBuilder work?
.NET Core 3.0 added Host.CreateDefaultBuilder under platform extensions which will provide a default initialization of IConfiguration which provides default configuration for the app in the following order:
appsettings.jsonusing the JSON configuration provider.appsettings.Environment.jsonusing the JSON configuration provider. For example:
appsettings.Production.jsonorappsettings.Development.json- App secrets when the app runs in the Development environment.
- Environment variables using the Environment Variables configuration provider.
- Command-line arguments using the Command-line configuration provider.
Further Reading – MS Docs
- App startup in ASP.NET Core
- Configuration in ASP.NET Core
- Use multiple environments in ASP.NET Core