The Health Checks are essential. Your app exposes them as HTTP endpoints.
Such an endpoint indicates if your app is “healthy” or “unhealthy”. Health checks may also include checks for the health of the API’s dependencies, such as databases, external services, caching systems, etc.
Health Checks can be used by alerting and monitoring systems to provide real-time visibility into the API’s health status. They are also commonly used for traffic routing and load balancing.
ASP.NET Core offers Health Check middleware for easy configuration. You register the Health Check service and map the endpoint for the basic configuration.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks();
var app = builder.Build();
app.MapHealthChecks("/healthz");
app.Run();
By default, there are no specific health checks to test dependencies. It returns a simple Healthy response in plain text with a 200 OK status code.
To create a custom health check, you have to implement the IHealthCheck interface.
public class MyHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
bool healthy = true;
if (healthy)
return Task.FromResult(
HealthCheckResult.Healthy("The API is healthy"));
return Task.FromResult(
HealthCheckResult.Unhealthy("The API is unhealthy"));
}
}
Registration of it is easy.
builder.Services
.AddHealthChecks()
.AddCheck<MyHealthCheck>("Custom");
If you use Entity Framework, you don’t need to write a custom Health Check to probe the connection with a database.
You need to add Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore NuGet package.
Then, register the Health Check for your DbContext.
builder.Services
.AddHealthChecks()
.AddCheck<MyHealthCheck>("Custom")
.AddDbContextCheck<MyContext>();
By default, the database health check calls EF’s CanConnectAsync method. You can change it using the AddDbContextCheck method overloads.
If your database is unavailable, you’ll get Unhealthy results.
In addition to Healthy and Unhealthy failure statuses, there is also a Degraded status. You can change it using the parameter in the AddCheck and AddDbContextCheck methods or the HealthCheckResult in the custom Health Check.
builder.Services
.AddHealthChecks()
.AddCheck<MyHealthCheck>("Custom")
.AddDbContextCheck<MyContext>(
failureStatus: HealthStatus.Degraded);
The built-in Health Checks are flexible. You can customize the output, failure status, and HTTP status code.
It’s a good practice to have Health Checks for your applications. If you don’t use them, it’s time to start. I hope this simple tutorial will help you with that.