ASP.NET Core cookbook · Beginner
Expose liveness and readiness health checks
Orchestrators restart healthy pods or route traffic to instances whose database is down.
Approach
Register checks with tags, map a liveness endpoint that runs no dependency checks and a readiness endpoint that checks the database with a timeout, and write a JSON summary.
Solution
using System.Text.Json;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("database", tags: ["ready"], timeout: TimeSpan.FromSeconds(2));
var app = builder.Build();
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready"),
ResponseWriter = (ctx, report) => ctx.Response.WriteAsync(JsonSerializer.Serialize(new
{
status = report.Status.ToString(),
checks = report.Entries.ToDictionary(e => e.Key, e => e.Value.Status.ToString()),
})),
});
app.Run();
public class DatabaseHealthCheck(IConfiguration config) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
{
try
{
await Task.Delay(10, ct); // replace with a real "SELECT 1" using your connection
return HealthCheckResult.Healthy();
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy("database unreachable", ex);
}
}
}
Pitfalls
- Dependency checks in liveness probes; a database outage then restarts every pod.
- Expensive checks run on every probe; keep them cheap or cache results briefly.
- Exposing detailed health output (connection strings, exception messages) publicly.
Variations
- The
AspNetCore.HealthChecks.*packages provide ready-made checks for PostgreSQL, Redis and more. - Publish health status to monitoring with
IHealthCheckPublisher.
Further reading: Health checks
Reference: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks
More ASP.NET Core recipes
- Accept file uploads with size and type limits
- Add OpenTelemetry traces and metrics
- Apply EF Core migrations safely during deployment
- Bind and validate options at startup
- Cache responses with output caching and evict by tag
- Call external APIs with typed HttpClients and resilience
- Configure CORS for a browser front end
- Generate OpenAPI documents with Microsoft.AspNetCore.OpenApi