Set environment variables
Define ASPNETCORE_ENVIRONMENT and your own variables without editing web.config by hand.
Environment variables are name–value pairs passed to your application when it starts. They let you change configuration without publishing the application again, and they are a good place for secrets such as connection strings and API keys, because they are not stored in the files you deploy.
Add a variable
Open Environment variables
In the Control Panel open your website, choose Scripting and then Environment variables.
Add the name and value
Fill in Name and Value and click Add.
Restart the application
Changes apply on the next application start. Click Restart application so that your application picks up the new values.
Each variable belongs to one website and is visible only to that website. Values that look like secrets are masked in the list; click Show to reveal them.
Use them in ASP.NET Core
ASP.NET Core reads environment variables into IConfiguration automatically, and they override the values from appsettings.json.
Use a double underscore __ for nested sections. A variable named ConnectionStrings__Default overrides this value:
{
"ConnectionStrings": {
"Default": "..."
}
}
In the same way Mail__Host maps to Mail:Host. A whole configuration section can be moved to environment variables like this:
{
"Mail": {
"Host": "smtp.local",
"Port": 25,
"Username": "test",
"Password": "test123"
}
}
| Name | Value |
|---|---|
Mail__Host |
smtp.prod |
Mail__Port |
25 |
Mail__Username |
produser |
Mail__Password |
prodpass |
The same application can then run in development, testing and production without any change to appsettings.json. More about the naming rules is in the Microsoft documentation.
A value from an environment variable is read as usual:
var connectionString = builder.Configuration.GetConnectionString("Default");
Any variable can also be read directly:
var apiKey = Environment.GetEnvironmentVariable("MY_API_KEY");
ASPNETCORE_ENVIRONMENT
The variable ASPNETCORE_ENVIRONMENT set to Production, Staging or Development decides which appsettings.{Environment}.json file your application loads and how it behaves.
Warning
Do not leave a public website in Development. In this mode an application shows detailed error pages, including parts of your source code, to every visitor.
Example: keep the connection string out of your files
Add the variable
Add a variable named
ConnectionStrings__Defaultwith your full database connection string as the value.Remove it from appsettings.json
Leave only non-secret defaults in the file you publish.
Restart the application
The application now reads the connection string from the environment and the secret stays out of the deployed files.
Other options
- A Node.js application can also read variables from a
.envfile placed in the application folder. - Variables can be defined in
web.configas well, but values set there are stored in a deployed file.