Thursday, December 4, 2025

thumbnail

Debugging ASP.NET Core Applications Effectively

 How to Debug ASP.NET Core Applications Effectively


Debugging ASP.NET Core requires a mix of IDE tools, runtime diagnostics, observability, and production-safe techniques. This guide covers what professionals usually do to isolate and fix bugs quickly.


1️⃣ Use the Right Visual Studio / VS Code Debugging Features

✔ Breakpoints (standard, conditional, tracepoints)


Conditional breakpoints:


i == 42 && model.IsValid



Hit counts, filters, and function breakpoints make debugging large codebases easier.


✔ Debugging asynchronous code


Use:


Parallel Tasks window


Tasks and Async Call Stack windows


Configure Just My Code and “Enable .NET Framework Source Stepping” if needed


This helps track async/await flow and avoid confusion in multithreaded systems.


✔ Attach to process


Useful when:


Running on IIS/IIS Express


Running in Docker


Debugging background services hosted inside ASP.NET Core


2️⃣ Use Logging Effectively (Structured Logs)


ASP.NET Core’s built-in logging is powerful when used correctly:


✔ Structure your logs:

logger.LogInformation("Order {OrderId} processed for {User}", id, userId);


Best logging providers:


Serilog + Seq / Kibana / Application Insights


NLog


Built-in Console provider for local debugging


Logging guidance:


Use LogTrace and LogDebug for development


Use LogError and LogCritical for failures


Correlate logs using TraceId and RequestId (ASP.NET Core does this automatically)


3️⃣ Enable Application Insights / OpenTelemetry for Deep Observability

What you gain:


Distributed traces


Dependency calls tracking


SQL timings and failures


Request latency percentiles


Exception mapping


Live metrics and performance counters


Minimal setup:

builder.Services.AddApplicationInsightsTelemetry();



Or for vendor-neutral:


builder.Services.AddOpenTelemetry()

    .WithTracing(builder => builder.AddAspNetCoreInstrumentation());


4️⃣ Debug HTTP Pipelines With Developer Exception Page


Enable in development:


if (app.Environment.IsDevelopment())

{

    app.UseDeveloperExceptionPage();

}



This gives:


Full stack trace


Route info


Query/form data


Cookies


Request headers


Never enable it in production.


5️⃣ Inspect Middleware Pipeline Issues


Many bugs occur inside the middleware pipeline.


Use:

app.Use(async (ctx, next) =>

{

    logger.LogInformation("Entering middleware");

    await next();

    logger.LogInformation("Exiting middleware");

});



Check:


Order of Use/Map/MapWhen


Short-circuited pipelines


Exception handling middleware placement


Authentication/authorization middleware order


6️⃣ Use Developer Tools for Client–Server Debugging

Browser DevTools:


Inspect network calls, CORS errors, 4xx/5xx, large payloads


Check HTTPS/HTTP3, compression, caching


Postman / HTTP REPL / curl:


Useful for:


Invalid model binding


Body serialization issues


Authentication token failures


Testing raw JSON payloads


7️⃣ Debug EF Core & Database Problems

Enable EF Core logs:

optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);


Detect:


Slow queries


N+1 queries


Misconfigured lazy loading


Connection pool exhaustion


Use:


SQL Server Profiler


EF Core Power Tools


Application Insights dependency logs


8️⃣ Debugging in Docker / Kubernetes

For Docker:

docker exec -it <container> bash



Then inspect:


dotnet dump


dotnet trace


dotnet counters


container logs (docker logs)


For Kubernetes:

kubectl logs pod-name

kubectl exec -it pod-name -- bash

kubectl port-forward



Attach remote debuggers (VS + Dev Tunnels / Azure Dev Spaces where applicable).


9️⃣ Use .NET CLI Diagnostic Tools (Production-Safe)


These tools help diagnose issues without restarting the app.


✔ dotnet-trace


Performance tracing (CPU, GC, exceptions)


✔ dotnet-counters


Live metrics (requests/sec, thread pool, allocations)


✔ dotnet-dump


Memory dumps + SOS debugging


✔ dotnet-gcdump


GC analysis


✔ dotnet-monitor


Exports runtime traces + integrates with Kubernetes; ideal for ASP.NET Core APIs.


๐Ÿ”Ÿ Debug Configuration & Environment Issues

Common problems:


Wrong appsettings.*.json loaded


Missing environment variables


Incorrect DI lifetime (Transient vs Scoped vs Singleton)


Misordered middleware


Wrong URL bindings (Kestrel / reverse proxy)


Inspect using:


app.Environment.EnvironmentName



Use logging to print configuration at startup.


1️⃣1️⃣ Exception Handling Best Practices

Centralized exception handling:

app.UseExceptionHandler("/error");



Inside controller:


[Route("/error")]

public IActionResult HandleError() =>

    Problem();



Avoid:

❌ swallowing exceptions

❌ catching generic Exception without logging

❌ throwing during DI setup or middleware construction without clarity


1️⃣2️⃣ Debugging Authentication/Authorization

Enable identity logs:

"Logging": {

  "IncludeScopes": false,

  "LogLevel": {

    "Microsoft.AspNetCore.Authentication": "Debug",

    "Microsoft.AspNetCore.Authorization": "Debug"

  }

}



Check:


Expired tokens


Clock drift


Incorrect JWT issuer/audience


Cookie settings (SameSite, Secure, domain)


Identity server configuration


1️⃣3️⃣ Debugging Performance Issues


Use:

๐Ÿ”น dotnet-trace

๐Ÿ”น PerfView

๐Ÿ”น Application Insights Profiler

๐Ÿ”น ANTS Performance Profiler

๐Ÿ”น BenchmarkDotNet (for small isolated methods)


Look for:


High GC usage


Thread pool starvation


Blocking sync code in async methods


Slow database calls


Large JSON serialization


Inefficient LINQ


๐ŸŽฏ Summary: The Effective Debugging Workflow


Reproduce with logs, breakpoints, and HTTP inspection


Check middleware ordering and configuration


Use structured logs + correlation


Isolate API layer vs EF/database layer


Use .NET diagnostics (dump, trace, counters)


Run profiling tools for performance issues


Use distributed tracing for microservices


Verify configuration/environment issues


Fix and validate with automated tests

Learn Dot Net Course in Hyderabad

Read More

How to Perform Load Testing on .NET Applications

Introduction to Integration Testing in Full Stack .NET

Unit Testing ASP.NET Core Applications

Testing and Debugging

Visit Our Quality Thought Institute in Hyderabad

Get Directions 

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive