.NET 7 Health Check
In this article we will be covering how we can implement Health Check in .NET 7
You can watch the full video on youtube
Why do health check:
- everything fails, all the time: its always better to be prepared
- No matter what architecture you have utilised to create your solution there is always an option of 3rd party which might fail and bring down the application
- For any problem that might happen a health check will notify you sooner and give you indication of what the problem is
- better user experience so in case there is a major failure we can redirect the user to a fix is in the process rather giving them any error screen
- health check within k8s and container will help the services which are running them to manage the container life cycle, so i might stop a container and create a new instance instead
Create new WebApi
dotnet new webapi -n ApiHealthTest
Inside our Program.cs we need to add the following
// add health check service
builder.Services.AddHealthChecks();
// creating the health check endpoint
app.MapHealthChecks("/health");
by adding these 2 lines of code our application will inform us if the app is running as or not.
But this is not always helpful what happen if we want to check the health for our database, see we are able to connect to it? or a 3rd party api that we might be using?
For this we need to create a custom health check which will be responsible for accomplishing this.
To create a custom health check we need to utilise the IHealthCheck interface which is provided for us. Within the interface we need to add the health implementation in the CheckHealthAsync method.
Now inside the root directory let us create a new folder called services and inside the Services folder will create a new folder called Health.
To do an API call we are going to be using RESTSharp nuget package which will allow us to do http calls.
dotnet add package RestSharp
Inside the Health folder we will create a new class called ApiHealthCheck and let us add the following
using Microsoft.Extensions.Diagnostics.HealthChecks;
using RestSharp;
namespace ApiHealthTest.Services.Health;public class ApiHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext ctx, CancellationToken cancellationToken = default)
{
var isOK = Random.Shared.Next(0, 100) % 2 == 0; var url = "<https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random>"; var client = new RestClient(url); var request = new RestRequest(url, Method.Get);
request.AddHeader("X-RapidAPI-Key", "5ff609da3emsh1aac2e828573722p1630a0jsn594945591efb");
request.AddHeader("X-RapidAPI-Host", "matchilling-chuck-norris-jokes-v1.p.rapidapi.com"); var response = client.Execute(request);
// call an endpoint and based on the result if its 200 or not found show a result use rest sharp if (response.IsSuccessful)
{
return Task.FromResult(HealthCheckResult.Healthy());
}
else
{
return Task.FromResult(HealthCheckResult.Unhealthy());
}
}
}
Now we need to register our custom health check in the program.cs
builder.Services.AddHealthChecks().AddCheck<ApiHealthCheck>("ApiHealth");
We can add as many health check as we need to our application
We can now run our application and check the endpoint and we can see that our application is healthy and our api is healthy
Now let us take this a step further by installing the following package
dotnet add package AspNetCore.HealthChecks.UI.Client --version 6.0.5
Next we need to update our Program.cs to utilise the new package
builder.Services.AddHealthChecks()
.AddCheck<ApiHealthCheck>("ApiHealth",
tags: new string[] { "api" });
app.MapHealthChecks("/health", new HealthCheckOptions()
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
Now we should be able to view our API health for each of the services that we have.
Please add your questions in the comments down below