ASP.NET - Health Checks and Application Diagnostics in ASP.NET Core

Health Checks and Application Diagnostics are important features in ASP.NET Core that help developers monitor, analyze, and maintain the health and performance of web applications. Modern applications often run on cloud platforms, containers, or distributed systems where continuous monitoring is essential. ASP.NET Core provides built-in tools and middleware that allow developers to detect failures, track application behavior, and ensure that services are operating correctly.

Health Checks are mainly used to verify whether an application and its dependent services are functioning properly. Application Diagnostics, on the other hand, focuses on collecting logs, performance data, error details, request tracing, and runtime information to troubleshoot and optimize the application.


Importance of Health Checks

In enterprise applications, multiple services work together such as:

  • Databases

  • APIs

  • Authentication services

  • Message queues

  • Cloud storage

  • Background jobs

If one service fails, the entire application may stop functioning correctly. Health Checks help identify these failures early.

Common benefits include:

  • Detecting database connection failures

  • Monitoring external APIs

  • Ensuring application availability

  • Supporting automatic recovery in cloud environments

  • Helping load balancers route traffic only to healthy instances

  • Improving DevOps monitoring and deployment processes


ASP.NET Core Health Checks Architecture

ASP.NET Core provides built-in middleware for health monitoring through the namespace:

Microsoft.Extensions.Diagnostics.HealthChecks

The system works using:

  1. Health Check Services

  2. Health Check Middleware

  3. Health Check Endpoints

  4. Custom Health Check Classes

  5. Health Status Reports


Installing Required Package

In most ASP.NET Core applications, health checks are already included.

If required, install:

dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks

For specific services like SQL Server:

dotnet add package AspNetCore.HealthChecks.SqlServer

Basic Health Check Configuration

Health checks are registered in Program.cs.

Example:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHealthChecks();

var app = builder.Build();

app.MapHealthChecks("/health");

app.Run();

Explanation:

  • AddHealthChecks() registers health check services.

  • MapHealthChecks("/health") creates an endpoint.

  • Accessing /health returns application health status.


Health Check Response

When the application is healthy:

Healthy

Possible statuses:

Status Meaning
Healthy Application is functioning correctly
Degraded Application is partially working
Unhealthy Critical failure detected

Monitoring Database Health

Applications heavily depend on databases. ASP.NET Core can monitor database connectivity.

Example:

builder.Services.AddHealthChecks()
    .AddSqlServer(
        connectionString:
        builder.Configuration.GetConnectionString("DefaultConnection"));

This checks:

  • Database connectivity

  • SQL Server availability

  • Query execution capability

If the database becomes unavailable, the health endpoint reports failure.


Checking External APIs

Applications often use third-party APIs such as:

  • Payment gateways

  • Weather services

  • Authentication providers

Health checks can verify whether external APIs are accessible.

Example:

builder.Services.AddHealthChecks()
    .AddUrlGroup(
        new Uri("https://api.example.com"),
        name: "External API");

Custom Health Checks

Developers can create custom health checks for application-specific logic.

Example scenario:

  • Verify disk space

  • Check memory usage

  • Validate cache availability

  • Monitor background services


Creating a Custom Health Check

Step 1: Create a Health Check Class

using Microsoft.Extensions.Diagnostics.HealthChecks;

public class MemoryHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        long memoryUsed = GC.GetTotalMemory(false);

        if (memoryUsed < 500000000)
        {
            return Task.FromResult(
                HealthCheckResult.Healthy("Memory usage normal"));
        }

        return Task.FromResult(
            HealthCheckResult.Unhealthy("High memory usage"));
    }
}

Step 2: Register the Health Check

builder.Services.AddHealthChecks()
    .AddCheck<MemoryHealthCheck>("Memory Check");

Health Check UI

Health check data can be displayed visually using dashboards.

Popular packages:

  • HealthChecks.UI

  • Prometheus

  • Grafana

These dashboards provide:

  • Real-time monitoring

  • Historical health data

  • Failure alerts

  • Service availability reports


Readiness and Liveness Probes

In containerized environments such as Docker and Kubernetes, health checks are divided into two categories.

Liveness Probe

Determines whether the application is alive.

If it fails:

  • Container may restart automatically.

Example:

  • Detect deadlocks

  • Detect crashed processes


Readiness Probe

Determines whether the application is ready to serve requests.

Example:

  • Database still initializing

  • Cache warming up

  • External services unavailable

Kubernetes uses readiness checks before routing traffic.


Example of Tagged Health Checks

builder.Services.AddHealthChecks()
    .AddSqlServer(
        connectionString,
        tags: new[] { "ready" });

Separate endpoints:

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = _ => false
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

Application Diagnostics in ASP.NET Core

Diagnostics refers to analyzing application behavior and detecting problems.

ASP.NET Core diagnostics include:

  • Logging

  • Exception handling

  • Request tracing

  • Performance monitoring

  • Distributed tracing

  • Metrics collection


Logging in ASP.NET Core

Logging records application events for debugging and monitoring.

ASP.NET Core supports providers like:

  • Console logging

  • Debug logging

  • Event Viewer

  • Azure Monitor

  • Serilog

  • NLog

Example:

var builder = WebApplication.CreateBuilder(args);

builder.Logging.ClearProviders();
builder.Logging.AddConsole();

Writing Logs

Example:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Index page accessed");

        return View();
    }
}

Log Levels

ASP.NET Core provides different logging levels.

Log Level Purpose
Trace Detailed debugging information
Debug Development debugging
Information General application flow
Warning Potential problems
Error Application errors
Critical Serious failures

Exception Handling Middleware

ASP.NET Core provides centralized error handling.

Example:

app.UseExceptionHandler("/Home/Error");

Developer exception page:

app.UseDeveloperExceptionPage();

This displays detailed errors during development.


Distributed Tracing

Modern applications use microservices. Tracking requests across services is difficult.

Distributed tracing helps:

  • Track request flow

  • Identify bottlenecks

  • Detect service failures

  • Analyze latency

ASP.NET Core supports:

  • OpenTelemetry

  • Application Insights

  • Jaeger

  • Zipkin


Performance Monitoring

Performance diagnostics monitor:

  • CPU usage

  • Memory consumption

  • Request execution time

  • Database query performance

  • Thread usage

ASP.NET Core provides built-in metrics and EventCounters.


Middleware for Request Logging

Example custom middleware:

app.Use(async (context, next) =>
{
    Console.WriteLine($"Request: {context.Request.Path}");

    await next();

    Console.WriteLine($"Response Status: {context.Response.StatusCode}");
});

This helps track incoming requests and responses.


Diagnostic Tools

Useful tools for ASP.NET Core diagnostics include:

Tool Purpose
dotnet-trace Collect runtime traces
dotnet-counters Monitor performance counters
dotnet-dump Analyze memory dumps
Visual Studio Diagnostics Debugging and profiling
Application Insights Cloud monitoring
Grafana Metrics visualization

Health Checks in Cloud Environments

Cloud platforms use health checks extensively.

Examples:

  • Azure App Service

  • AWS ECS

  • Google Kubernetes Engine

  • Docker Swarm

Benefits:

  • Auto-scaling

  • Self-healing systems

  • Zero-downtime deployments

  • Load balancing support


Best Practices

Keep Health Checks Lightweight

Health checks should execute quickly.

Avoid:

  • Heavy database queries

  • Large file operations

  • Long-running computations


Separate Critical and Non-Critical Checks

Critical:

  • Database

  • Authentication

Non-critical:

  • Analytics services

  • Reporting modules


Use Secure Health Endpoints

Do not expose detailed system information publicly.

Protect endpoints using:

  • Authentication

  • IP restrictions

  • API gateways


Enable Structured Logging

Structured logging improves searching and filtering.

Example:

_logger.LogInformation(
    "User {UserId} logged in at {Time}",
    userId,
    DateTime.UtcNow);

Real-World Example

Consider an e-commerce application.

Health checks monitor:

  • SQL database

  • Payment gateway

  • Inventory service

  • Redis cache

  • Email service

Diagnostics track:

  • Failed orders

  • Slow APIs

  • Payment failures

  • Memory leaks

  • High CPU usage

If a payment service fails:

  • Health checks mark service as degraded.

  • Monitoring tools trigger alerts.

  • Load balancers redirect traffic if necessary.


Advantages of Health Checks and Diagnostics

Feature Benefit
Health Monitoring Detects failures early
Logging Simplifies debugging
Diagnostics Improves performance
Tracing Tracks requests across services
Metrics Helps capacity planning
Alerts Enables quick incident response

Conclusion

Health Checks and Application Diagnostics are essential components of modern ASP.NET Core applications. Health checks ensure that services and dependencies are functioning correctly, while diagnostics provide visibility into application behavior, performance, and failures. Together, they improve system reliability, maintainability, scalability, and operational efficiency.

In cloud-native and enterprise environments, these features play a critical role in automation, monitoring, and self-healing systems. Proper implementation of health checks and diagnostics helps organizations maintain stable and high-performing applications while reducing downtime and troubleshooting effort.