In part 1 we create our basic ASP.NET Core health check and then in part 2 we changed from plain text “Healthy” or “Unhealthy” to a json response that let us know the stauts of each health check.
In our previous post, we have only have a single health check so it has been ok to have all health checks run when we hit our health check endpoint. However, if we had multiple health checks we are going to want to be able to run them by themselves as well as run the whole suite.
In this post, we will are going to add the ability to selectively run our health checks and create endpoints that will run either a set of health checks or all of the health checks.
If you have not implemented the example health check from part 1 and part 2, please do so first or download code from previous post
To demonstrate selectively running of health checks, we need to add a second health check.
Create second health check called ExampleHealthCheck2.cs
ExampleHealthCheck2.cs
Add the following code to the ExampleHealthCheck2.cs file. This is a copy of the ExampleHealthCheck.cs with the messages changed.
namespace AspNetCoreHealthCheckExample;
using Microsoft.Extensions.Diagnostics.HealthChecks;
public class ExampleHealthCheck2Async : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
return Task.FromResult(
HealthCheckResult.Healthy("Health Check 2 Msg Here."));
}
catch (Exception)
{
return Task.FromResult(
new HealthCheckResult(
context.Registration.FailureStatus, "Unhealthy Check 2 Msg Here."));
}
}
}
The next task we need to do is add tags when we tell ASP.NET Core about our health checks by adding the tags parameter and giving 1 or more tags names.
|
|
The last item we need to do is to create new health check endpoints that only run health checks that match a given tag by using the Predicate parameter.
|
|
Now when you navigate to the /health
endpoint it will run all health checks and when you navigate to /health/example
and /health/example2
it will only run the health checks that match the tag.
In our next post in this series, we will update our endpoint mapping to use a generic endpoint that provides filtering and returns json with a single line of code.
You can also read more about ASP.NET Core Health Checks in the docs