Health Check in Aspnet Core - Part 1
What are health checks and why it is important?
Health checks are one of the crucial features that every API should implement. It helps in monitoring different applications 24 * 7 and reduces the turnaround time in case of any failure.
In Aspnet Core, it is exposed by an application using an HTTP endpoint. Monitoring applications like New-Relic or Sentry.io can invoke these endpoints in regular intervals and raise necessary notifications in case of any failure.
Health checks can be used in the following scenarios.
It can be used by Load Balancers to check the health of a particular application.
It can also provide a detailed description of disk usage or other physical server resources.
It can check the status of external endpoints as well.
There are three different HealthStatus
value
Healthy
UnHealthy
Degraded
This article is using .Net 6 Minimal Api. The complete source code could be found at Health Check in Aspnet Core, in the "Part-1" branch
Download below mentioned Nuget packages
dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks
Open Program.cs file and configure health-check in it.
builder.Services.AddHealthChecks();
Once the configuration is done then we have to map the health check endpoint
app.MapHealthChecks("/health-check");
The complete code is
var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddHealthChecks(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.MapHealthChecks("/health-check"); app.Run();
Press F5 to run the application and navigate to /health-check endpoint. The following screen will be displayed.
This endpoint only displays the current status of the application whether it is Healthy
or not. If there are some issues in the application, then it either display Unhealthy
or Degraded
. As you might be thinking this only provides a piece of basic information, but this feature can be used in other scenarios as well like checking database connection.
There are various NuGet packages available for different types of health check which we are going to cover in the next section.
Subscribe to my newsletter
Read articles from Rahul Pandey directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by