Run certain .NET Core health checks depending on tags

2.3k views Asked by At

I added .NET Core Health Checks to my app.

I want to use tags to only run one check if it's a basic check or all checks for a more detailed check.

This is what I've got:

services.AddHealthChecks()
                        .AddCheck("Check1", () => HealthCheckResult.Healthy("Service Is Healthy!"), tags: new[] { "basic", "full" })
                        .AddCheck<CheckLogsAreHealthy>("Check2", tags: new[] { "full" })
                        .AddCheck<CheckLvcConnectionStatus>("Check3", tags: new[] { "full" })

I thought my URL should look like this:

http://localhost:4000/api/health?tags=basic

or

http://localhost:4000/api/health?tags=full

But this does not seem to be the case. How do I run each check?

1

There are 1 answers

1
Arnaud Leclerc On BEST ANSWER

This might be a late answer and I hope you already found your solution, but calling AddHealthChecks does not automatically create a URL for your health checks, it is only registering them.

To create an endpoint for your health checks, you have to call the MapHealthChecks method on IEndpointRouteBuilder. This method also accepts options with a Predicate field where you can pass a predicate to filter the health checks to execute. For example, the following example filters the registered health checks based on the tags and creates a /health/basic and a /health/full endpoints, each one executing the health checks having basic or full in their tags.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
   app.UseEndpoints(endpoints =>
   {      
      endpoints.MapHealthChecks("/health/basic", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
      {
         Predicate = registration => registration.Tags.Contains("basic")
      });
      
      endpoints.MapHealthChecks("/health/full", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
      {
         Predicate = registration => registration.Tags.Contains("full")
      });
   });
...
}