Need to know if your app is healthy? Health checks provide monitoring endpoints automatically.
Setup:
// Program.cs
builder.Services.AddHealthChecks()
.AddDbContextCheck() // Check database
.AddUrlGroup(new Uri("https://api.example.com"), "External API"); // Check external dependency
var app = builder.Build();
app.MapHealthChecks("/health");
Test:
curl http://localhost:5000/health # Healthy response: 200 OK # Unhealthy: 503 Service Unavailable
Custom Health Check:
public class MemoryHealthCheck : IHealthCheck
{
public Task CheckHealthAsync(HealthCheckContext context)
{
var allocatedMemory = GC.GetTotalMemory(false);
var threshold = 1024 * 1024 * 1024; // 1 GB
return Task.FromResult(
allocatedMemory < threshold
? HealthCheckResult.Healthy("Memory usage normal")
: HealthCheckResult.Unhealthy("Memory usage high")
);
}
}
builder.Services.AddHealthChecks()
.AddCheck("memory");
Kubernetes/Docker use this to know when to restart containers!
