How to add health checks to your ASP.NET application

Health checks in ASP.NET Core are a way to monitor the health of your application and its dependencies.


Adding health checks to your ASP.NET application

Health checks in ASP.NET Core are a way to monitor the health of your application and its dependencies. They can be used to check the status of various components, such as databases, external services, and more. To add health checks to your ASP.NET application, you need to add them to your service collection like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddCheck("My custom check", () => HealthCheckResult.Healthy("The check is healthy!"));
}

There are multiple built-in checks available, such as checking the status of a database or an external service. You can also create your own custom checks by implementing the IHealthCheck interface. Many of the existing health checks can be found here: https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks. Below example shows how to add a Redis health check from the AspNetCore.HealthChecks.Redis package:

services.AddHealthChecks()
    .AddRedis("<host_name>:<port>,password=<password>", name: "redis", tags: new[] { "redis" }); // The connection string should come from your configuration

After adding the health checks, you can expose them via MapHealthChecks - WebApplication extension method. This will create an endpoint that can be used to check the health of your application. In this case /health endpoint will be created:

app.MapHealthChecks("/health");

The above code will only return a simple status code (200 OK) if the health checks pass. If any of the checks fail, it will return a 503 Service Unavailable status code. You can also customize the response format, add tags, and more by configuring the HealthCheckOptions parameter. You can also specify the response format for the health checks. For example, you can use the ResponseWriter property to customize the response. Package AspNetCore.HealthChecks.UI.Client has a built-in response writer that formats the health check results in a way that is easy to read and understand. Here's how you can use it:

app.MapHealthChecks(HealthEndpointPath, new HealthCheckOptions()
{
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

This will format the health check results in a JSON format that includes the status of each check, the duration, and any additional information provided by the checks. A sample response will look like this:

{
    "status": "Healthy",
    "totalDuration": "00:00:00.0967127",
    "entries": {
        "redis": {
            "data": {},
            "duration": "00:00:00.0928458",
            "status": "Healthy",
            "tags": []
        }
    }
}