How to add health checks to your ASP.NET application
Health checks let ASP.NET Core report whether your application and its dependencies are working. Learn how to register built-in and custom checks, format the response, and split liveness and readiness endpoints for Kubernetes.
Your application might be running, but is it actually working? It could be up and serving requests while its database connection is broken or a cache it relies on is unreachable. Health checks answer that question. They expose an HTTP endpoint that reports the status of the app and its dependencies, so load balancers, container orchestrators like Kubernetes, and monitoring tools can decide whether to send it traffic, restart it, or alert someone.
ASP.NET Core has health checks built in, and the middleware ships in the shared framework — no extra package is needed for the basics.
Registering health checks
Health checks are registered on the service collection and then exposed with MapHealthChecks. With the minimal hosting model, that looks like this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy("The app is running"));
var app = builder.Build();
app.MapHealthChecks("/health");
app.Run();If you're still using a Startup class, the registration goes in ConfigureServices and the mapping goes in Configure:
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy("The app is running"));
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapHealthChecks("/health"));
}By default, the /health endpoint returns a plain-text body containing the overall status, along with a matching status code:
| Status | Response code | Meaning |
|---|---|---|
Healthy | 200 OK | Everything is working. |
Degraded | 200 OK | Working, but something isn't quite right (e.g. a slow dependency). |
Unhealthy | 503 Service Unavailable | At least one check failed — the app shouldn't receive traffic. |
The overall status is the worst status of all the individual checks.
Checking dependencies
A check that only says "I'm running" isn't very informative. The real value comes from checking the things your application depends on. The community-maintained AspNetCore.Diagnostics.HealthChecks project provides ready-made checks for most common dependencies — SQL Server, PostgreSQL, Redis, RabbitMQ, Azure services, AWS services, and many more.
For example, to check Redis using the AspNetCore.HealthChecks.Redis package:
builder.Services.AddHealthChecks()
.AddRedis(
builder.Configuration.GetConnectionString("Redis")!,
name: "redis",
tags: new[] { "redis", "ready" });The connection string comes from configuration rather than being hard-coded, so the check always tests the same Redis instance the application itself uses. (We'll come back to the tags parameter shortly.)
If you use Entity Framework Core, the Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore package adds a check that verifies your DbContext can connect to its database:
builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>(tags: new[] { "ready" });Writing a custom health check
When there's no package for what you need, implement IHealthCheck. Here's a check that reports Degraded when the server is running low on disk space:
public class DiskSpaceHealthCheck : IHealthCheck
{
private const long MinimumFreeBytes = 1L * 1024 * 1024 * 1024; // 1 GB
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
var drive = new DriveInfo(Path.GetPathRoot(AppContext.BaseDirectory)!);
var data = new Dictionary<string, object>
{
["freeBytes"] = drive.AvailableFreeSpace
};
if (drive.AvailableFreeSpace >= MinimumFreeBytes)
{
return Task.FromResult(HealthCheckResult.Healthy("Enough disk space available", data));
}
// Use the failure status configured at registration (Unhealthy by default)
return Task.FromResult(new HealthCheckResult(
context.Registration.FailureStatus,
"Disk space is running low",
data: data));
}
}Register it with AddCheck<T>. The failureStatus parameter lets you decide how serious a failure is — running low on disk is worth knowing about, but probably not a reason to take the app out of rotation:
builder.Services.AddHealthChecks()
.AddCheck<DiskSpaceHealthCheck>("disk", failureStatus: HealthStatus.Degraded);Health check classes are resolved from dependency injection, so you can inject an HttpClient, a DbConnection, options, or anything else you need through the constructor.
Returning a detailed JSON response
The plain-text response is fine for a load balancer, but a human (or a dashboard) usually wants to know which check failed. You can customise the output using the ResponseWriter property of HealthCheckOptions. The AspNetCore.HealthChecks.UI.Client package includes a ready-made writer that serialises every check result as JSON:
app.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});The response now includes the status, duration, tags, and any data returned by each individual check:
{
"status": "Healthy",
"totalDuration": "00:00:00.0967127",
"entries": {
"redis": {
"data": {},
"duration": "00:00:00.0928458",
"status": "Healthy",
"tags": ["redis", "ready"]
}
}
}Be aware that detailed output can reveal information about your infrastructure. If the endpoint is publicly reachable, consider restricting it — for example with .RequireHost("*:8081") to serve it only on an internal port, or .RequireAuthorization() to require an authenticated caller.
Separate liveness and readiness endpoints
Once you have several checks, you'll often want different endpoints for different purposes. Kubernetes is the classic example, with two distinct probes:
- Liveness — Is the process alive? If this fails, Kubernetes restarts the container. It should not check dependencies: if the database goes down, restarting every instance of your app won't fix it, and can make things worse.
- Readiness — Is the app ready to receive traffic? If this fails, Kubernetes stops routing requests to the pod until it recovers, but leaves it running. This is where dependency checks belong.
The tags we added earlier make this easy. Use the Predicate option to choose which checks run on each endpoint:
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
// Run no checks at all — a 200 response simply proves the process is responsive
Predicate = _ => false
});
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
// Only run checks tagged "ready", e.g. the Redis and DbContext checks above
Predicate = check => check.Tags.Contains("ready")
});Then point the Kubernetes probes at those endpoints in your deployment manifest:
livenessProbe:
httpGet:
path: /health/live
port: 8080
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
periodSeconds: 5
failureThreshold: 3Tips
- Keep checks fast. Probes run frequently. A check that runs a heavy query every few seconds adds real load — prefer something cheap like
SELECT 1or a simple ping. - Set timeouts. A dependency that hangs can make the health check hang too. Pass the
CancellationTokenthrough to any I/O, and consider thetimeoutparameter available onAddCheck. - Be deliberate about
Degraded. It returns200 OKby default, so traffic keeps flowing. It's ideal for "worth alerting on, but not worth failing over" situations. You can change the mapping with theResultStatusCodesoption if you need different behaviour.