Appearance
Are you an LLM? You can read better optimized documentation at /troubleshooting/debugging.md for this page in Markdown format
Debugging guide
This document provides a comprehensive guide to debugging the TheExampleApp application. It covers the tools, techniques, and common scenarios developers will encounter while maintaining and extending the codebase. A solid understanding of these practices is essential for efficient troubleshooting and development.
Visual Studio debugging
The primary debugging environment for this ASP.NET Core application is Visual Studio. Leveraging its powerful debugging features is the most effective way to diagnose issues. The project is pre-configured for a seamless debugging experience.
Launch Profiles and Development Mode
The launchSettings.json file defines how the application starts when you press F5 in Visual Studio. There are two main profiles:
- IIS Express: Runs the application under the IIS Express web server. The browser will launch at
http://localhost:59989/. - TheExampleApp: Runs the application as a self-hosted process using the Kestrel web server at
http://localhost:3000/.
Both profiles are configured to launch the application in the Development environment.
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
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
Running in the Development environment is critical because it enables the Developer Exception Page. As configured in Startup.cs, this page provides detailed stack traces and request information directly in the browser when an unhandled exception occurs.
csharp:TheExampleApp/Startup.cs
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
if (env.IsDevelopment())
{
// Enables the detailed exception page for easier debugging.
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
// In non-development environments, a user-friendly error page is used.
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
Core Debugging Techniques
While debugging, make full use of Visual Studio's standard features:
- Breakpoints: Set breakpoints in your C# code (e.g., in Page Models,
Startup.cs, or custom services) to pause execution and inspect the application's state. - Inspecting Variables: Hover over variables or use the
Locals,Autos, andWatchwindows to examine their values at a breakpoint. - Call Stack: Use the Call Stack window to understand the execution path that led to the current breakpoint.
- Immediate Window: Execute C# expressions on the fly to evaluate variables or test methods within the current debugging context.
Logging
The application uses the standard ASP.NET Core logging framework, which is configured in appsettings.json and initialized in Program.cs.
Log Levels and Configuration
By default, the application is configured to log only Warning level messages and higher. This is defined in appsettings.json.
json:TheExampleApp/appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
// ...
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
During development, this is often insufficient. To get more detailed logs, you should override this setting. The recommended practice is to create an appsettings.Development.json file and set the log level to Debug or Information.
Example appsettings.Development.json:
json
{
"Logging": {
"LogLevel": {
"Default": "Information", // Shows general application flow
"Microsoft": "Warning", // Keeps framework logs less verbose
"TheExampleApp": "Debug" // Enables detailed logs from our application code
}
}
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
For more details on application configuration, see the application settings documentation.
Viewing Logs
When debugging in Visual Studio, logs are automatically routed to the Debug output window. You can also configure other logging providers (e.g., Console, File) in Program.cs if needed.
Browser developer tools
Even for a server-side rendered application, the browser's developer tools (F12) are indispensable for debugging.
- Network Tab: This is the most useful tool for this application.
- Inspect the status code of page loads. A
500error indicates a server-side exception. - Check the response headers. For example, you can verify
Set-Cookieheaders when the session state is created or modified. - View the raw HTML response sent from the server before the browser parses it.
- Inspect the status code of page loads. A
- Console Tab: While the app doesn't use a heavy client-side framework, any JavaScript errors from minor scripts or libraries will appear here.
- Application Tab: Use this to inspect cookies, including the session cookie (
.AspNetCore.Session), to verify its presence and attributes.
Common debugging scenarios
This section covers debugging strategies for specific, complex parts of the application.
Page Model Debugging
The application uses Razor Pages for its primary UI structure. Business logic for each page is contained within its PageModel class. To debug page behavior, set breakpoints inside the handler methods (e.g., OnGet(), OnPostAsync()).
A key example is the Error.cshtml.cs page model, which is responsible for handling and displaying application-wide errors. Setting a breakpoint in its OnGet method allows you to inspect the original exception that triggered the error page.
csharp:TheExampleApp/Pages/Error.cshtml.cs
public class ErrorModel : PageModel
{
// ...
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
// Get the last exception that occurred.
var ex = HttpContext?.Features?.Get<IExceptionHandlerFeature>()?.Error; // Breakpoint here to inspect 'ex'
if(ex is ContentfulException)
{
ContentfulException = ex as ContentfulException;
RequestId = ContentfulException.RequestId;
}
}
}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
For more information on the application's structure, refer to the Razor Pages documentation.
Contentful Query Debugging
As Contentful is the primary data source, issues related to content fetching are common.
1. Configuration and API Errors
Most Contentful issues stem from incorrect configuration or API errors.
- Check Configuration: Verify that the
SpaceId,DeliveryApiKey, andPreviewApiKeyinappsettings.jsonare correct. EnsureUsePreviewApiis set appropriately for the environment. - Catch
ContentfulException: The application is designed to catchContentfulException. As shown in theErrorModelabove, when this exception occurs, it is captured and its details (including the crucialRequestId) are made available to the error page. ThisRequestIdis essential if you need to contact Contentful support.
For a detailed guide on resolving these issues, see Troubleshooting Contentful Issues.
2. Staging Environment Request Routing
The application includes a custom HttpClientHandler to redirect Contentful API calls to a staging endpoint when a StagingHost environment variable is set. If you are experiencing issues in a staging environment, this is a critical place to debug.
Set a breakpoint inside the SendAsync method of StagingMessageHandler to verify that the request URI is being rewritten correctly.
csharp:TheExampleApp/Startup.cs
public class StagingMessageHandler : HttpClientHandler
{
public string StagingHost { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var regex = new Regex("contentful");
// Set a breakpoint on the next line to inspect the original and rewritten URI.
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
2
3
4
5
6
7
8
9
10
11
12
Session State and Localization Inspection
The application uses a complex, custom RequestCultureProvider to manage internationalization (i18n) based on query string parameters and session state. This logic, located in Startup.cs, is a common area for bugs related to language display.
Debugging Steps:
- Set Breakpoints: Place breakpoints inside the
CustomRequestCultureProviderlambda inStartup.Configure. - Inspect
HttpContext: When a breakpoint is hit, inspects.Request.Queryto see if thelocalekey is present. - Inspect Session: Examine
s.Sessionto see the values ofLOCALE_KEYandFALLBACK_LOCALE_KEY. You can do this using the Watch window in Visual Studio by evaluatings.Session.GetString("locale"). - Trace Logic: Step through the provider's logic to understand how it validates the locale against Contentful, determines a fallback, and sets the final culture for the request.
csharp:TheExampleApp/Startup.cs
// ... inside app.UseRequestLocalization
new CustomRequestCultureProvider(async (s) => {
// Set a breakpoint here to begin tracing localization logic.
if (s.Request.Query.ContainsKey(LOCALE_KEY))
{
// ... logic to validate locale and set session values ...
}
return null;
}),
// ...1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
This process will help you diagnose why the wrong language is being displayed or why a fallback is/is not being triggered correctly. For general issues, consult the Common Issues page.