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 the environment variables used to configure TheExampleApp. Understanding and correctly setting these variables is crucial for local development, testing, and production deployment.
ASPNETCORE_ENVIRONMENT: Controlling environment-specific behavior
The ASPNETCORE_ENVIRONMENT variable is a cornerstone of the ASP.NET Core configuration system. It dictates which environment-specific configuration files are loaded and enables conditional logic within the application code.
The application recognizes the following primary values for this variable:
Development: Used for local development. Enables features like the developer exception page and detailed logging.Staging: Used for pre-production environments. Enables specific logic for connecting to staging services.Production: The default for live deployments. Enables performance and security optimizations like exception handling pages and HTTPS redirection.Heroku: A custom environment name used in the project'sDockerfile. This behaves similarly toProductionbut can be used for Heroku-specific configurations if needed.
Implementation Details
During local development, this variable is set in TheExampleApp/Properties/launchSettings.json:
json
"profiles": {
"TheExampleApp": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:3000/"
}
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
For containerized deployments, it is set within the Dockerfile:
dockerfile
# ...
FROM microsoft/aspnetcore:2.1
WORKDIR /app
ENV ASPNETCORE_ENVIRONMENT=Heroku
COPY --from=builder /app .
ENTRYPOINT ["dotnet", "TheExampleApp.dll"]1
2
3
4
5
6
2
3
4
5
6
The application uses this variable in Startup.cs to alter its behavior, for example, by enabling the developer exception page only in the Development environment.
csharp
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
// Production/Staging error handling and HTTPS redirection
app.UseExceptionHandler("/Error");
}
// ...
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
Contentful credentials: ContentfulOptions__* variables for API keys
The application's primary content is sourced from a Contentful space. Connection details are configured via the ContentfulOptions section in appsettings.json. To securely override these settings in different environments, the application uses environment variables.
The ASP.NET Core configuration provider maps environment variables with a double underscore (__) to nested JSON properties. The following variables are used to configure the Contentful SDK:
| Environment Variable | appsettings.json Property | Description |
|---|---|---|
ContentfulOptions__DeliveryApiKey | DeliveryApiKey | Required. The API key for accessing published content from the Contentful Delivery API. |
ContentfulOptions__PreviewApiKey | PreviewApiKey | Required. The API key for accessing draft/unpublished content from the Contentful Preview API. |
ContentfulOptions__SpaceId | SpaceId | Required. The unique identifier for the Contentful space containing the application's content. |
ContentfulOptions__UsePreviewApi | UsePreviewApi | A boolean (true/false) that toggles between the Delivery and Preview APIs. Defaults to false. |
These variables directly override the values found in appsettings.json. For a complete guide on setting up the Contentful integration, see the Contentful Setup documentation.
StagingHost: Custom Contentful API host for staging
When the application is running in the Staging environment (ASPNETCORE_ENVIRONMENT=Staging), it can be configured to point to a custom Contentful API endpoint (e.g., a private staging instance) using the StagingHost environment variable.
This is a special case, as the variable is read directly using Environment.GetEnvironmentVariable rather than through the standard IConfiguration pipeline.
| Environment Variable | Description |
|---|---|
StagingHost | The base hostname (e.g., contentful.staging.my-company.com) to use instead of the public Contentful API hosts. |
Implementation Details
If ASPNETCORE_ENVIRONMENT is Staging and StagingHost is set, the application registers a custom HttpClient with a message handler that rewrites outgoing Contentful API requests to the specified host.
csharp
// In ConfigureServices method
if (CurrentEnvironment.IsStaging())
{
var host = Environment.GetEnvironmentVariable("StagingHost");
if (!string.IsNullOrEmpty(host))
{
services.AddSingleton((ip) =>
{
var stagingHandler = new StagingMessageHandler
{
StagingHost = host
};
return new HttpClient(stagingHandler);
});
}
}
// ...
public class StagingMessageHandler : HttpClientHandler
{
public string StagingHost { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var regex = new Regex("contentful");
var req = regex.Replace(request.RequestUri.ToString(), StagingHost, 1);
request.RequestUri = new Uri(req);
return await base.SendAsync(request, cancellationToken);
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Configuration hierarchy: Environment variables vs. appsettings.json
The application follows the standard ASP.NET Core configuration hierarchy. Settings are loaded from multiple sources, with later sources overriding earlier ones. The effective order for this project is:
appsettings.json(base configuration, contains default values)appsettings.{ASPNETCORE_ENVIRONMENT}.json(e.g.,appsettings.Development.json)- User Secrets (during development, for sensitive data)
- Environment Variables
- Command-line arguments
This means that any environment variable you set will always take precedence over values defined in appsettings.json or appsettings.Development.json. This is the primary mechanism for injecting secrets and environment-specific settings into the application for deployment.
For example, setting the environment variable ContentfulOptions__UsePreviewApi=true will force the application to use the Preview API, even though appsettings.json sets it to false.
Setting environment variables: On different platforms
The method for setting environment variables depends on your operating system and deployment platform.
Local Development (via
launchSettings.json): For Visual Studio ordotnet run, the easiest way is to edit theenvironmentVariablessection inTheExampleApp/Properties/launchSettings.json. This is ideal for non-sensitive, development-time configuration.Windows (Command Prompt):
bash# For the current session set ContentfulOptions__SpaceId=your_space_id # Persist for the current user setx ContentfulOptions__SpaceId "your_space_id"1
2
3
4
5Linux / macOS (Bash/Zsh):
bash# For the current session export ContentfulOptions__SpaceId='your_space_id' # Persist by adding the line above to your ~/.bashrc or ~/.zshrc file1
2
3
4Docker: Environment variables can be set at build time using the
ENVinstruction in aDockerfileor at runtime using the-eflag. For more details, see the Docker deployment guide.bash# Runtime example docker run -e "ContentfulOptions__DeliveryApiKey=your_api_key" -p 8080:80 the-example-app1
2Heroku: Heroku uses a system called "Config Vars" to manage environment variables. These can be set via the Heroku Dashboard (under your app's "Settings" tab) or using the Heroku CLI. For more details, see the Heroku deployment guide.
bashheroku config:set ContentfulOptions__DeliveryApiKey=your_api_key -a your-heroku-app-name1
Required vs. optional
Not all environment variables are required in all situations. The following table clarifies which variables are essential for the application to run.
| Variable | Required? | Notes |
|---|---|---|
ASPNETCORE_ENVIRONMENT | Required | Determines the application's runtime mode. Set to Development locally and Production or Heroku in deployed environments. |
ContentfulOptions__DeliveryApiKey | Required | The application will fail to start or respond to requests without a valid Delivery API key. |
ContentfulOptions__PreviewApiKey | Required | Even when UsePreviewApi is false, the Contentful SDK may require this key for initialization. It is essential if UsePreviewApi is set to true. |
ContentfulOptions__SpaceId | Required | The application cannot query for content without a Space ID. |
ContentfulOptions__UsePreviewApi | Optional | Defaults to false from appsettings.json. Only needs to be set if you want to enable the preview API in a deployed environment. |
StagingHost | Optional (Required for Staging) | Only has an effect if ASPNETCORE_ENVIRONMENT is set to Staging. If you are running a staging environment, this variable is effectively required. |
Failure to provide the required Contentful variables will result in a ContentfulException or other service resolution errors during application startup. For initial setup, refer to the Installation Guide.
Security best practices
Never commit secrets to source control. The appsettings.json file in this project contains example Contentful API keys for a demo space. While these credentials are functional for demonstration purposes, they should never be used in production. In a real-world scenario, all API keys should be removed from appsettings.json and managed securely through environment variables or secret management tools.
- Local Development: Use the User Secrets Manager for .NET Core. This tool stores sensitive data in a separate JSON file on your local machine, outside of the project directory. This is the recommended approach for storing
ContentfulOptionskeys during development. - Production/Staging: Always inject secrets as environment variables through your hosting platform's secure mechanism (e.g., Heroku Config Vars, Azure App Service Application Settings, AWS Parameter Store, Docker Secrets). This prevents secrets from being exposed in your codebase or deployment artifacts.
Development vs. production
Your configuration strategy will differ significantly between development and production environments.
Development Strategy
ASPNETCORE_ENVIRONMENT:Development- Configuration Source:
launchSettings.jsonforASPNETCORE_ENVIRONMENT, User Secrets for Contentful API keys. - Goal: Enable easy debugging, rapid iteration, and prevent secrets from being committed to Git. The
appsettings.Development.jsonfile can be used to override non-sensitive settings like logging levels.
Production Strategy
ASPNETCORE_ENVIRONMENT:ProductionorHeroku- Configuration Source: All sensitive or environment-specific values (all
ContentfulOptions__*variables) must be set as environment variables by the hosting platform. - Goal: Maximize security, performance, and stability. Ensure that no sensitive data is present in the built container image or source code repository.
ContentfulOptions__UsePreviewApishould be explicitly set tofalseor left unset to use the default.