Appearance
Are you an LLM? You can read better optimized documentation at /reference/configuration_reference.md for this page in Markdown format
Configuration reference
This document provides an exhaustive reference for all configuration options available in TheExampleApp. It is intended for developers responsible for maintaining, running, and deploying the application. A thorough understanding of this configuration is essential for managing different environments and troubleshooting issues.
The application leverages the standard ASP.NET Core configuration system, which uses a hierarchical approach to load settings from various sources. The order of precedence is as follows:
appsettings.json(base configuration)appsettings.{Environment}.json(e.g.,appsettings.Development.json,appsettings.Staging.json)- Environment Variables
- Command-line arguments
Settings from later sources in this list will override settings from earlier ones.
Complete configuration guide
The application's configuration is primarily managed through appsettings.json files and environment variables. This system provides a flexible way to adjust application behavior for different deployment environments such as Development, Staging, and Production.
The core configurable components are:
- Logging: Controls the verbosity and output of application logs.
- Contentful SDK: Manages the connection to the Contentful headless CMS, which is the primary data source for the application.
- Environment-Specific Behavior: Custom logic that activates based on the current runtime environment, such as the Staging proxy for Contentful API calls.
- Session Management: Configures session timeout and behavior.
- Localization: Manages multi-language support and locale fallback behavior.
For more details on specific configuration areas, refer to the following documents:
appsettings.json schema
The appsettings.json files are the foundation of the application's configuration. The base appsettings.json contains default or production-safe values, while environment-specific files override these for local development or staging.
Logging section
The Logging section configures the built-in ASP.NET Core logging framework. The LogLevel subsection determines the minimum severity of messages to be logged for different categories.
Example from appsettings.Development.json and appsettings.Staging.json:
json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Default: The default log level for all categories. In Development and Staging, this is set toDebugfor maximum verbosity. The baseappsettings.jsonsets this toWarningfor cleaner production logs.SystemandMicrosoft: Override the log level for specific namespaces, providing more granular control over framework-level logging.
ContentfulOptions section
This section contains all the necessary credentials and settings to connect to the Contentful CMS. These settings are bound to an options class and used to initialize the Contentful client.
Example from base appsettings.json:
json
{
"ContentfulOptions": {
"DeliveryApiKey": "df2a18b8a5b4426741408fc95fa4331c7388d502318c44a5b22b167c3c1b1d03",
"PreviewApiKey": "10145c6d864960fdca694014ae5e7bdaa7de514a1b5d7fd8bd24027f90c49bbc",
"SpaceId": "qz0n5cdakyl9",
"UsePreviewApi": false
}
}1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Example from appsettings.Staging.json:
json
{
"ContentfulOptions": {
"DeliveryApiKey": "3048cf48001c0a5f2d0cdd2135f4fa7b80f93e36452381a0a32b0f81c8ca8063",
"PreviewApiKey": "d477447bd0ba58db88009e5eae6d033d524730a700010952f30300d7810b861a",
"SpaceId": "9leupbwh43vu",
"UsePreviewApi": false
}
}1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
The following table details each property within the ContentfulOptions object:
| Property | Type | Description - |
|---|---|---|
SpaceId | string | The unique identifier for the Contentful space. This tells the SDK which content repository to connect to. - |
DeliveryApiKey | string | The API key for the Content Delivery API (CDA). This key provides read-only access to published content and is safe to use in client-side applications. - |
- | |
PreviewApiKey| string | The API key for the Content Preview API (CPA). This key provides access to both published and draft (unpublished) content. It should be kept secret and only used in secure environments. - | |UsePreviewApi| boolean | A flag that determines which API to use. Iftrue, thePreviewApiKeyis used to fetch content, including drafts. Iffalse, theDeliveryApiKeyis used to fetch only published content. This should always befalsein production. - |
Custom Contentful Client Registration
It is important to note that Startup.cs contains a custom registration for the IContentfulClient. This is not standard behavior for the contentful.aspnetcore package.
csharp
// TheExampleApp/Startup.cs
// ...
// This would normally not be needed, but since we want to load our ContentfulOptions from memory if they're changed within the application
// we provide our own implementation logic for the IContentfulClient
services.AddSingleton<IContentfulOptionsManager, ContentfulOptionsManager>();
services.AddTransient<IContentfulClient, ContentfulClient>((ip) => {
var client = ip.GetService<HttpClient>();
var options = ip.GetService<IContentfulOptionsManager>().Options;
var contentfulClient = new ContentfulClient(client,
options);
var version = typeof(Startup).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
contentfulClient.Application = $"app the-example-app.csharp/{version}; {contentfulClient.Application}";
return contentfulClient;
});
// ...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
This custom implementation was added to allow for in-memory changes to the ContentfulOptions. While this feature might be used for specific admin functionality, developers should be aware that configuration is not strictly read-only after startup.
Session configuration
The application uses ASP.NET Core session state to store user-specific data, such as the selected locale and visited lessons. Session configuration is defined in Startup.cs:ConfigureServices:
csharp
// TheExampleApp/Startup.cs:84
services.AddSession(options => {
// IdleTimeout is set to a high value to confirm to requirements for this particular application.
// In your application you should use an IdleTimeout that suits your application needs or stick to the default of 20 minutes.
options.IdleTimeout = TimeSpan.FromDays(2);
});1
2
3
4
5
6
7
2
3
4
5
6
7
Key settings:
IdleTimeout: Set to 2 days for this application. This unusually high value ensures that locale preferences and lesson progress persist across user sessions. The default ASP.NET Core value is 20 minutes, which is more appropriate for most applications.
Important: Session data is stored in-memory by default and will be lost when the application restarts. For production deployments with multiple server instances, consider implementing a distributed session store (e.g., Redis).
Localization configuration
The application supports multiple languages using ASP.NET Core's request localization framework. Supported locales are defined in Startup.cs:43:
csharp
// TheExampleApp/Startup.cs:43
public static List<CultureInfo> SupportedCultures = new List<CultureInfo>
{
//When adding supported locales make sure to also add a static translation files for the locale under /wwwroot/locales
new CultureInfo("en-US"),
new CultureInfo("de-DE"),
};1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Currently supported locales:
en-US(English - United States)de-DE(German - Germany)
Locale selection and fallback mechanism
The application implements a sophisticated locale selection mechanism in Startup.cs:Configure that integrates with Contentful's locale system:
- Query string parameter: Users can specify a locale using the
?locale=xx-XXquery parameter. - Contentful locale validation: The selected locale is validated against the locales available in the Contentful space.
- Fallback chain: If the selected Contentful locale is not supported by the application, the system walks through Contentful's fallback chain to find a supported locale.
- Session storage: The selected locale is stored in the session using the key
"locale". If a fallback locale is used for static strings, it is stored under"fallback-locale".
Locale priority order:
localequery parameter (if valid in Contentful)- Locale stored in session
- Default locale (
en-US)
This mechanism allows the application to display content in locales that Contentful supports, even if the application itself doesn't have static translations for that locale, by falling back to the closest supported language for UI strings.
URL rewriting and redirects
The application uses ASP.NET Core's URL rewriting middleware to handle redirects and HTTPS enforcement. Configuration is in Startup.cs:Configure:
HTTPS redirection (production only)
In non-development environments, the application enforces HTTPS by checking the X-Forwarded-Proto header:
csharp
// TheExampleApp/Startup.cs:118
options.Add((c) => {
var request = c.HttpContext.Request;
if(request.Headers.ContainsKey("X-Forwarded-Proto") && request.Headers["X-Forwarded-Proto"] == "http")
{
var response = c.HttpContext.Response;
response.StatusCode = StatusCodes.Status301MovedPermanently;
c.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] = "https://" + request.Host + request.Path + request.QueryString;
}
});1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
This rule issues a 301 permanent redirect from HTTP to HTTPS when running behind a reverse proxy (e.g., load balancer) that sets the X-Forwarded-Proto header.
Course URL normalization
The application redirects legacy course URLs to the canonical format:
csharp
// TheExampleApp/Startup.cs:129
options.AddRedirect("courses/(.*)/lessons$", "/courses/$1");1
2
3
2
3
This rule removes the trailing /lessons segment from course URLs, redirecting /courses/{slug}/lessons to /courses/{slug}.
Custom middleware
The application registers custom middleware components in the request pipeline:
csharp
// TheExampleApp/Startup.cs:238
app.UseBreadcrumbs();
app.UseDeeplinks();1
2
3
4
2
3
4
UseBreadcrumbs(): Middleware for managing breadcrumb navigation. This component tracks the navigation path through the application to provide contextual breadcrumb trails to users.UseDeeplinks(): Middleware for handling deep links into the application. This ensures that direct links to specific content (e.g., course lessons) work correctly with the application's routing system.
These middleware components are registered near the end of the pipeline, just before MVC routing is configured.
Environment variables
Environment variables are the preferred method for supplying sensitive data and for overriding appsettings.json values in deployed environments (Staging, Production).
ASPNETCORE_ENVIRONMENT
This is the most critical environment variable. It dictates which appsettings.{Environment}.json file is loaded and enables environment-specific logic within the application.
Development: Used for local development. Enables the Developer Exception Page and more verbose logging.Staging: Used for the staging environment. Enables theStagingHostproxy logic.Production: The default if not set. Uses production-safe settings (e.g., error handler page, less verbose logging).
This variable is checked frequently in Startup.cs:
csharp
// TheExampleApp/Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
// ...
}
else
{
// ...
app.UseExceptionHandler("/Error");
}
// ...
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ContentfulOptions__*
To override the nested ContentfulOptions from appsettings.json, use environment variables with a double underscore (__) as a delimiter. This is standard ASP.NET Core convention.
ContentfulOptions__DeliveryApiKey: Overrides the Delivery API key.ContentfulOptions__PreviewApiKey: Overrides the Preview API key.ContentfulOptions__SpaceId: Overrides the Contentful Space ID.ContentfulOptions__UsePreviewApi: Overrides the flag to use the Preview API (e.g.,trueorfalse).
For more information, see the deployment documentation.
StagingHost (staging only)
This is a custom environment variable used only when ASPNETCORE_ENVIRONMENT is set to Staging. It redirects all outgoing requests to the Contentful API to a different host. This is useful for testing against a staging-specific proxy or mock server.
The implementation is in Startup.cs and StagingMessageHandler:
csharp
// TheExampleApp/Startup.cs
// 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
31
32
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
31
32
Gotcha: If the application is running in Staging mode and the StagingHost variable is set, API calls will not go to *.contentful.com. This is a critical detail for troubleshooting data discrepancies in the staging environment.
launchSettings.json
The Properties/launchSettings.json file configures the local development environment when running the project from Visual Studio or using the dotnet run command. This file is not used in deployment.
json
// TheExampleApp/Properties/launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:56497/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "http://localhost:59989/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"TheExampleApp": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:3000/"
}
}
}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
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
Development profiles
This file defines multiple profiles for launching the application:
IIS Express: Runs the application using IIS Express. TheenvironmentVariablessection setsASPNETCORE_ENVIRONMENTtoDevelopment.TheExampleApp: Runs the application using the Kestrel web server directly (commandName: "Project"). It also sets the environment toDevelopmentand specifies the application URL (http://localhost:3000/).
Developers can modify these profiles or add new ones to test different startup configurations, such as running locally with ASPNETCORE_ENVIRONMENT set to Staging to debug the StagingHost functionality.