Section 5 of 6

Health Checks

🎯 What You'll Learn

  • What are health checks
  • Basic health checks
  • Database health checks
  • Custom health checks
  • Health check UI

What are Health Checks?

Health checks monitor the health of your application and its dependencies (database, external APIs, etc.) to ensure everything is working correctly.

Basic Health Check

Program.cs C#
builder.Services.AddHealthChecks();

var app = builder.Build();

app.MapHealthChecks("/health");
Test Health Check Bash
curl https://localhost:5001/health

Database Health Check

Install Package Bash
dotnet add package AspNetCore.HealthChecks.SqlServer
Program.cs C#
builder.Services.AddHealthChecks()
    .AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));

Custom Health Check

StockHealthCheck.cs C#
public class StockHealthCheck : IHealthCheck
{
    private readonly InvenTrackDbContext _context;

    public StockHealthCheck(InvenTrackDbContext context)
    {
        _context = context;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default)
    {
        try
        {
            var lowStockCount = await _context.Products
                .CountAsync(p => p.Quantity < p.ReorderLevel, cancellationToken);

            if (lowStockCount > 10)
            {
                return HealthCheckResult.Degraded(
                    $"{lowStockCount} products have low stock");
            }

            return HealthCheckResult.Healthy("Stock levels are good");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("Stock check failed", ex);
        }
    }
}
Register Custom Health Check C#
builder.Services.AddHealthChecks()
    .AddCheck<StockHealthCheck>("stock_check");

Health Check Response

Custom Response Writer C#
using Microsoft.Extensions.Diagnostics.HealthChecks;

app.MapHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = async (context, report) =>
    {
        context.Response.ContentType = "application/json";
        
        var result = JsonSerializer.Serialize(new
        {
            status = report.Status.ToString(),
            checks = report.Entries.Select(e => new
            {
                name = e.Key,
                status = e.Value.Status.ToString(),
                description = e.Value.Description
            })
        });
        
        await context.Response.WriteAsync(result);
    }
});

Health Check UI

Install Package Bash
dotnet add package AspNetCore.HealthChecks.UI
dotnet add package AspNetCore.HealthChecks.UI.InMemory.Storage
Program.cs C#
builder.Services.AddHealthChecksUI().AddInMemoryStorage();

app.MapHealthChecksUI();
appsettings.json JSON
{
  "HealthChecksUI": {
    "HealthChecks": [
      {
        "Name": "InvenTrack",
        "Uri": "https://localhost:5001/health"
      }
    ],
    "EvaluationTimeInSeconds": 10
  }
}

Access UI at: https://localhost:5001/healthchecks-ui

Key Takeaways

  • Health checks: Monitor application health
  • AddHealthChecks(): Register service
  • MapHealthChecks(): Expose endpoint
  • Database checks: AddSqlServer()
  • Custom checks: Implement IHealthCheck
  • Health Check UI: Visual dashboard