Appearance
Are you an LLM? You can read better optimized documentation at /deployment/environment_variables.md for this page in Markdown format
Environment variables
This document provides a comprehensive guide to managing application configuration using environment variables in TheExampleApp. A proper understanding of this configuration strategy is essential for development, deployment, and maintenance.
Environment configuration
The application leverages the built-in ASP.NET Core Configuration system, which provides a flexible, hierarchical approach to managing settings. This system aggregates configuration values from various sources in a specific order of precedence. For this project, the typical order is:
appsettings.json(base configuration, committed to source control)appsettings.{Environment}.json(e.g.,appsettings.Development.json, for environment-specific overrides)- User Secrets (for local development)
- Environment Variables
- Command-line arguments
Environment variables are the primary mechanism for providing configuration to the application in deployed environments (Staging, Production). They allow for secure management of secrets and environment-specific settings without modifying the application's source code.
The application's Startup.cs class is injected with an IConfiguration instance, which contains the merged configuration from all providers.
csharp
// File: TheExampleApp/Startup.cs
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
CurrentEnvironment = env;
}
public IConfiguration Configuration { get; }
private IHostingEnvironment CurrentEnvironment { get; set; }
// ...
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
For more details on the base file-based configuration, see the Application Settings documentation.
ASP.NET Core environment
The behavior of the application can change significantly based on the runtime environment. This is controlled by the ASPNETCORE_ENVIRONMENT environment variable. ASP.NET Core recognizes three standard environments by default:
Development: Used for local development. Enables features like the Developer Exception Page for detailed error diagnostics.Staging: Typically used for a pre-production environment that should closely mirror production.Production: The live environment. Features are optimized for performance and security, and detailed error information is suppressed.
The application code uses the IHostingEnvironment service to execute environment-specific logic.
csharp
// File: TheExampleApp/Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
// Enables a detailed error page for easier debugging during development.
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
// In non-development environments, use a generic error handler.
app.UseExceptionHandler("/Error");
}
// ...
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Custom Environments
ASP.NET Core allows you to define custom environment names beyond the standard Development, Staging, and Production. Any custom environment name that is not Development will follow the non-development code path (using the generic error handler instead of the detailed exception page).
This application uses a custom Heroku environment in its Dockerfile, which is set as the default when running in Docker containers. Like other non-development environments, it will use the generic error handler and production-like behavior.
The application has specific logic for the Staging environment, which reads another environment variable, StagingHost, to redirect Contentful API requests. This is a powerful pattern for testing against a staging content source.
csharp
// File: TheExampleApp/Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// ...
if (CurrentEnvironment.IsStaging())
{
var host = Environment.GetEnvironmentVariable("StagingHost");
if (!string.IsNullOrEmpty(host))
{
// Custom HttpClient to reroute requests in Staging
services.AddSingleton((ip) =>
{
var stagingHandler = new StagingMessageHandler
{
StagingHost = host
};
return new HttpClient(stagingHandler);
});
}
}
// ...
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Contentful configuration via environment
The application's connection to the Contentful headless CMS is configured via the ContentfulOptions section in appsettings.json.
json
// File: TheExampleApp/appsettings.json
{
// ...
"ContentfulOptions": {
"DeliveryApiKey": "df2a18b8a5b4426741408fc95fa4331c7388d502318c44a5b22b167c3c1b1d03",
"PreviewApiKey": "10145c6d864960fdca694014ae5e7bdaa7de514a1b5d7fd8bd24027f90c49bbc",
"SpaceId": "qz0n5cdakyl9",
"UsePreviewApi": false
}
}1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
To override these settings in a deployed environment, you must use environment variables. The ASP.NET Core configuration provider maps hierarchical JSON keys to environment variables by replacing the colon (:) with a double underscore (__).
The following table shows the mapping from appsettings.json keys to the required environment variable names:
| JSON Key | Environment Variable Name | Description |
|---|---|---|
ContentfulOptions:DeliveryApiKey | ContentfulOptions__DeliveryApiKey | The API key for accessing the Contentful Delivery API (published content). |
ContentfulOptions:PreviewApiKey | ContentfulOptions__PreviewApiKey | The API key for accessing the Contentful Preview API (draft content). |
ContentfulOptions:SpaceId | ContentfulOptions__SpaceId | The ID of the Contentful space to connect to. |
ContentfulOptions:UsePreviewApi | ContentfulOptions__UsePreviewApi | Set to true to use the Preview API instead of the Delivery API. |
Setting these variables in your hosting environment will automatically override the default values from appsettings.json at runtime. This is the correct and secure way to provide production credentials.
Platform-specific variables
The method for setting environment variables depends on the hosting platform. Below are instructions for the platforms relevant to this project.
Heroku
Heroku manages environment variables through "Config Vars". You can set them via the Heroku Dashboard (under your app's Settings tab) or using the Heroku CLI.
Example using Heroku CLI:
bash
# Set the Contentful Space ID and Delivery API Key
heroku config:set ContentfulOptions__SpaceId=<your_space_id>
heroku config:set ContentfulOptions__DeliveryApiKey=<your_delivery_api_key>
# Set the environment to Production
heroku config:set ASPNETCORE_ENVIRONMENT=Production1
2
3
4
5
6
2
3
4
5
6
For more information, refer to the Heroku Deployment Guide.
Azure App Service
In Azure App Service, environment variables are managed as "Application settings" in the Configuration blade of your App Service resource in the Azure Portal.
- Name: Use the hierarchical key name with a colon, e.g.,
ContentfulOptions:DeliveryApiKey. Azure will correctly expose this to the .NET Core application. - Value: The secret value for the key.
- Deployment slot setting: It is recommended to check this box for settings like API keys, so that each slot (e.g., staging, production) can have its own unique values.
For more details, see the Azure Deployment Guide.
Docker
When running the application in a Docker container, you can pass environment variables using the -e or --env flag with the docker run command.
Example using docker run:
bash
docker run -d -p 8080:80 \
-e "ASPNETCORE_ENVIRONMENT=Production" \
-e "ContentfulOptions__SpaceId=<your_space_id>" \
-e "ContentfulOptions__DeliveryApiKey=<your_delivery_api_key>" \
-e "ContentfulOptions__UsePreviewApi=false" \
your-image-name:latest1
2
3
4
5
6
2
3
4
5
6
The project's Dockerfile uses the ENV instruction to set ASPNETCORE_ENVIRONMENT=Heroku as the default environment. Variables passed with -e at runtime will override values set with ENV in the Dockerfile.
For more on deployment strategies, see the Deployment Overview.
Security considerations
Properly managing secrets is critical to the security of the application.
WARNING: Never commit secrets to source control.
The appsettings.json file included in this repository contains example keys for demonstration purposes only. In any real-world scenario, these keys must be considered compromised and should be replaced.
The definitive security policy for this project is:
- Local Development: Use the .NET Secret Manager tool to store sensitive data like API keys. This keeps secrets out of the project directory and away from source control.
- Deployed Environments (Staging, Production): Use environment variables provided by the hosting platform (e.g., Heroku Config Vars, Azure Application Settings) to inject secrets at runtime. This is the industry-standard practice for securely managing credentials in cloud environments.
By adhering to this policy, you ensure that sensitive credentials are never exposed in the codebase, significantly improving the application's security posture.