All 15 Health Checks questions
More in Health Checks
Advertisement
ASP.NET Core › Health Checks

How do you implement a custom health check by implementing IHealthCheck, such as checking database connectivity?

Intermediate

Answer

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.

Common follow-ups: What's the difference between Degraded and Unhealthy, and how should consumers of the health endpoint react differently to each?;How do you set a timeout for an individual health check so a hanging dependency doesn't block the whole endpoint?