Appearance
Are you an LLM? You can read better optimized documentation at /troubleshooting/common_issues.md for this page in Markdown format
Common issues
This document provides solutions and explanations for frequently encountered problems during the development and maintenance of TheExampleApp. It is intended for developers on the team and assumes familiarity with the application's core technology stack.
Contentful Connection Errors
Connection issues with the Contentful headless CMS are a common source of errors, often manifesting as runtime exceptions or pages with no content.
Invalid API Credentials or Space ID
The most frequent cause of connection failure is incorrect or misconfigured Contentful credentials. The application loads these from multiple sources, which can be a point of confusion.
1. Default Configuration (appsettings.json)
On application startup, credentials are loaded from the ContentfulOptions section in appsettings.json. Ensure these values are correct for the target Contentful space.
json:TheExampleApp/appsettings.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
DeliveryApiKey: Used for accessing published content.PreviewApiKey: Used for accessing unpublished drafts.SpaceId: The unique identifier for your Contentful space.UsePreviewApi: A boolean that toggles which API key is used. Set totrueto view draft content.
2. Runtime Overrides (Session State)
The application features a unique mechanism, ContentfulOptionsManager, that allows for overriding the default credentials at runtime on a per-session basis. This is used by the settings page to allow developers to temporarily point the app at a different Contentful space.
csharp:TheExampleApp/Configuration/ContentfulOptionsManager.cs
/// <summary>
/// Gets the currently configured <see cref="ContentfulOptions"/> either from session, if present, or from the application configuration.
/// </summary>
public ContentfulOptions Options {
get {
var sessionString = _accessor.HttpContext.Session.GetString(nameof(ContentfulOptions));
if (!string.IsNullOrEmpty(sessionString))
{
return JsonConvert.DeserializeObject<ContentfulOptions>(sessionString);
}
return _options;
}
}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
If you are experiencing unexpected connection issues, clear your session cookies to ensure you are not using stale or incorrect credentials stored in the session. The IsUsingCustomCredentials property can be used during debugging to verify if session-based options are active.
Network Issues and Error Handling
If credentials are correct, the issue may be network-related. The application is configured to catch ContentfulException and display a detailed error page.
csharp:TheExampleApp/Pages/Error.cshtml.cs
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
// Get the last exception that occurred.
var ex = HttpContext?.Features?.Get<IExceptionHandlerFeature>()?.Error;
if(ex is ContentfulException)
{
ContentfulException = ex as ContentfulException;
RequestId = ContentfulException.RequestId;
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
When an error occurs, the error page will display the RequestId provided by the Contentful API. This ID is essential for debugging and should be included in any support tickets filed with Contentful.
For more details on setting up credentials, see the Contentful Setup Guide.
Missing Content
Pages appearing empty or throwing NullReferenceException in Razor views are typically symptoms of the Contentful API returning no data for a given query.
Causes for Null or Empty Contentful Responses
- Incorrect API Usage: Ensure the correct API (Delivery vs. Preview) is being used. If content is saved as a draft in Contentful, it will only be visible if
UsePreviewApiis set totrue. - Invalid Locale: The application's localization logic fetches content for a specific locale. If you request a locale that exists in the app but has no content entered in Contentful, the API will return entries with
nullfields. This is a common cause ofNullReferenceExceptionin views that don't check for null. - Unpublished Content: An entry might exist but is not published. It will not be returned by the Delivery API.
- Connection Errors: As described above, a failed connection will result in no data being passed to the view.
To debug, use a tool like Postman to query the Contentful API directly with the same credentials and query parameters used by the application. This helps isolate whether the issue is in the application logic or with the content itself. For debugging help, refer to the Debugging Guide.
Localization Issues
The application has a sophisticated but complex localization system that combines Contentful's locale settings with the application's static resource files.
Understanding the Locale Resolution Pipeline
The locale is determined on each request by a series of IRequestCultureProviders defined in Startup.cs. The primary logic resides in a custom provider.
- Query String Priority: The provider first checks for a
localekey in the query string (e.g.,?locale=de-DE). - Contentful Validation: It then makes an API call to
client.GetSpace()to fetch all available locales from Contentful. If the requested locale is not present in Contentful, the request falls back to the default culture (en-US). - Application Fallback Logic: If the locale is in Contentful but is not supported by the application's static resources (the
SupportedCultureslist inStartup.cs), the system traverses the locale's fallback chain within Contentful (e.g.,en-GBmight fall back toen-US). The first supported locale found in the chain is used for the UI culture (static strings), while the original requested locale is stored in the session to fetch content from Contentful.
csharp:TheExampleApp/Startup.cs
// ... inside Configure method
new CustomRequestCultureProvider(async (s) => {
if (s.Request.Query.ContainsKey(LOCALE_KEY))
{
// ...
var contentfulLocales = space.Locales;
if(contentfulLocales.Any(c => c.Code == locale) == false)
{
// Not a supported locale in Contentful, return the default.
return null;
}
if(SupportedCultures.Any(c => string.Equals(c.ToString(), locale, StringComparison.OrdinalIgnoreCase)) == false)
{
// The locale is supported in Contentful, but not by the application.
// Walk through the fallback chain to see if we find a supported locale there.
var fallback = GetNextFallbackLocale(contentfulLocales.FirstOrDefault(c => c.Code == locale));
// ...
}
// ...
}
// ...
})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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Common Pitfalls
- Mismatched Configurations: The
SupportedCultureslist inStartup.csmust be kept in sync with the embedded locale JSON files (e.g.,en-US.json). Adding a new language requires updating both. - Performance: The custom provider makes an async API call to Contentful on requests containing a
localequery parameter. This can introduce latency and should be considered for caching if it becomes a bottleneck. - Session Dependency: The chosen locale and its fallback are stored in the session. Issues with session state can lead to incorrect language display on subsequent requests.
Build Errors
Build errors are most likely to occur when setting up a new development environment due to the project's reliance on the older .NET Core 2.1 stack.
NuGet Restore Failures
The dotnet restore command (run automatically by Visual Studio or manually from the CLI) may fail if it cannot find the required packages. The project uses the Microsoft.AspNetCore.All version 2.1.5 metapackage, which may not be available in default, modern NuGet feeds.
Solution: Ensure your nuget.config file is configured to access the official nuget.org source. In some corporate environments, you may need to configure access to a legacy package feed.
If you encounter persistent restore issues, try clearing all NuGet caches:
bash
dotnet nuget locals all --clear1
For initial setup instructions, please see the Installation Guide.
Runtime Errors
Runtime errors can often be traced back to incorrect configuration in Startup.cs, particularly concerning middleware ordering and session state.
Session State Issues
Several core features, including the ContentfulOptionsManager and the custom localization provider, depend on ASP.NET Core Session State.
- Middleware Order: The
app.UseSession()call inStartup.Configureis critical. It must be placed before any middleware that accesses the session, such asapp.UseRequestLocalization()andapp.UseMvc(). - Idle Timeout: The session timeout is configured to an unusually long duration of two days. This was a specific project requirement. Be aware that in a typical application, this could lead to high memory consumption on the server.
csharp:TheExampleApp/Startup.cs
// In ConfigureServices
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);
});
// In Configure
// ...
app.UseStaticFiles();
app.UseSession(); // Must be before middleware that uses session.
app.UseRequestLocalization(...);
// ...
app.UseMvc(...);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
Middleware Ordering
The order of middleware registration in the Configure method is vital for correct application behavior. A misconfigured pipeline can lead to authentication problems, 404 errors, or unhandled exceptions.
Critical Order in Startup.Configure:
UseDeveloperExceptionPage()/UseExceptionHandler(): Should be registered very early to catch exceptions from later middleware.UseStaticFiles(): Placed early to serve static files quickly without going through other processing.UseSession(): As noted, must come before MVC and other custom middleware that reads session data.UseRequestLocalization(): Sets the culture for the request, which is needed by MVC for model binding and view rendering.UseMvc(): The final step that routes the request to a Razor Page or controller.
Docker Issues
The project includes a Dockerfile for containerization. Issues can arise from the base images, build process, or runtime environment configuration.
Analysis of the Dockerfile
The Dockerfile uses a multi-stage build, which is a best practice for creating optimized, smaller final images.
dockerfile:Dockerfile
# Stage 1: Build the application
FROM microsoft/dotnet:2.1-sdk AS builder
WORKDIR /src
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o /app/
# Stage 2: Create the final runtime image
FROM microsoft/aspnetcore:2.
WORKDIR /app
ENV ASPNETCORE_ENVIRONMENT=Heroku
COPY --from=builder /app .
ENTRYPOINT ["dotnet", "TheExampleApp.dll"]1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Potential Problems
- Malformed Base Image Tag: CRITICAL ERROR - The runtime base image tag is incomplete (
microsoft/aspnetcore:2.). This will cause Docker builds to fail as it's not a valid image tag. The tag needs to be corrected to a complete version (e.g.,microsoft/aspnetcore:2.1). - Deprecated Base Images: The
microsoft/dotnet:2.1-sdkandmicrosoft/aspnetcorebase images are for .NET Core 2.1, which is out of support. These images may contain unpatched security vulnerabilities. For long-term maintenance, an upgrade of the entire application stack to a supported .NET version (e.g., .NET 6 or 8) is strongly recommended. ASPNETCORE_ENVIRONMENT: The environment is hardcoded toHeroku. This is a non-standard value (compared toDevelopment,Staging, orProduction). This will cause the application to look for a configuration file namedappsettings.Heroku.jsonand can affect how certain framework features behave. Be aware of this when deploying or running the container.- Build Failures: If the
dotnet restorestep fails inside the container, it's often due to the Docker daemon being unable to reach NuGet feeds. Ensure the build environment has proper network access.
For more on deployment, see the Docker Deployment Guide.
Performance Problems
Performance issues like slow page loads or API timeouts are often related to the interaction with the external Contentful service.
Slow Page Loads
- API Latency: Every request that fetches data from Contentful is subject to network latency. Check the Contentful Status Page for any ongoing incidents.
- Complex Localization: As mentioned in the Localization section, the custom culture provider makes a blocking API call (
client.GetSpace()) to validate locales. This adds overhead to requests that include a?locale=query parameter. Caching the space's locale information would be a key optimization. - Large Content Payloads: Fetching a large number of entries or entries with many assets (images, videos) can increase response time. Optimize queries to fetch only the data needed for the current view.
API Timeouts
The application uses a default HttpClient for Contentful requests. Timeouts can occur if the Contentful API is slow to respond. While not explicitly configured in the provided code, you can adjust the HttpClient timeout during its registration in Startup.cs if needed.
Development Environment
Issues specific to the local development setup.
Staging Environment Configuration
The application has special logic for a "Staging" environment that redirects Contentful API calls. This is handled by the StagingMessageHandler.
csharp:TheExampleApp/Startup.cs
// In ConfigureServices
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);
});
}
}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
To run the application in a staging configuration that points to a different Contentful endpoint (e.g., a proxy or mock server), you must:
- Set
ASPNETCORE_ENVIRONMENT=Staging. - Set the
StagingHostenvironment variable to the target hostname (e.g.,my-staging-proxy.com).
Failure to set the StagingHost variable while in the Staging environment will result in the application using the default HttpClient and connecting to the production Contentful API.
For general debugging techniques, see the Debugging Guide.