ASP.NET Core › Health Checks
How do you implement a custom health check by implementing IHealthCheck, such as checking database connectivity?
IntermediateAnswer
Implement IHealthCheck's single CheckHealthAsync method, returning HealthCheckResult.Healthy(), .Degraded(), or .Unhealthy() (each optionally with a description and data dictionary) based on whatever logic determines the dependency's status -- register it via AddHealthChecks().AddCheck<T>("name") or the inline AddCheck("name", () => ...) overload for simple synchronous checks.
public class DatabaseHealthCheck(AppDbContext db) : IHealthCheck {
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default) {
try {
await db.Database.CanConnectAsync(ct);
return HealthCheckResult.Healthy("Database connection OK");
} catch (Exception ex) {
return HealthCheckResult.Unhealthy("Database connection failed", ex);
}
}
}
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("database");Real-world example An e-commerce API registers a custom DatabaseHealthCheck verifying it can actually connect to the database (not just that the connection string is configured), causing the /health endpoint to report Unhealthy during a database outage even while the app process itself is still running fine.