When your Web API is deployed to a cloud environment like Kubernetes or Azure App Service, the infrastructure needs to know if your API is actually "alive" or if it has crashed silently. Health Checks provide dedicated endpoints for the load balancer to continuously ping.
By default, ASP.NET Core can provide a simple "Liveness" probe returning an HTTP 200 "Healthy" string.
var builder = WebApplication.CreateBuilder(args);
// 1. Register the Health Checks service
builder.Services.AddHealthChecks();
var app = builder.Build();
// 2. Map the endpoint (Load balancers will ping URL/health)
app.MapHealthChecks("/health");
app.Run();
A server might be "alive", but if the SQL Database it depends on goes offline, the API is functionally useless. We must configure the Health Check to actually ping the database before reporting "Healthy".
# Install the official SQL Server Health Check package
dotnet add package AspNetCore.HealthChecks.SqlServer
builder.Services.AddHealthChecks()
// Instantly checks if the connection string works!
.AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
// Now, if you visit /health and SQL Server is down,
// the API returns an HTTP 503 Service Unavailable automatically.
Returning a plain-text "Healthy" or "Unhealthy" string is great for Kubernetes, but humans prefer a dashboard. Using the AspNetCore.HealthChecks.UI community package, you can generate a beautiful dashboard showing the real-time status of your API, DB, and Redis caches.
// 1. Add services
builder.Services.AddHealthChecksUI().AddInMemoryStorage();
// 2. Map the UI endpoint
app.MapHealthChecksUI(options =>
{
// The beautiful dashboard will live at URL/health-ui
options.UIPath = "/health-ui";
options.AddCustomStylesheet("wwwroot/custom-ui.css");
});
Q: "In Kubernetes, there is a strict distinction between a 'Liveness Probe' and a 'Readiness Probe'. How do we configure ASP.NET Core Health Checks to satisfy both requirements distinctly?"
Architect Answer: "A Liveness Probe asks 'Is the .NET process physically running?'. If it fails, Kubernetes restarts the pod. A Readiness Probe asks 'Is the API ready to accept traffic?'. If it fails, Kubernetes stops sending users to it, but doesn't restart it. We accomplish this using Health Check Tags. We create two separate `MapHealthChecks()` endpoints. `MapHealthChecks('/health/live')` contains NO database checks. It just returns 'Alive' instantly. `MapHealthChecks('/health/ready', new HealthCheckOptions { Predicate = check => check.Tags.Contains('db') })` specifically runs the SQL Server ping test. This prevents Kubernetes from infinitely restarting our server pod just because an external SQL server temporarily went offline."