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.

  1. It can be used by Load Balancers to check the health of a particular application.

  2. It can also provide a detailed description of disk usage or other physical server resources.

  3. 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

  1. Download below mentioned Nuget packages

     dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks
    
  2. Open Program.cs file and configure health-check in it.

     builder.Services.AddHealthChecks();
    
  3. Once the configuration is done then we have to map the health check endpoint

     app.MapHealthChecks("/health-check");
    
  4. 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.