Add Health Check in ASP.NET Core Applications

Health Check in ASPNET Core

In this article, we shall check how to implement the Health Check in ASP.NET Core Applications like API or MVC applications.

A health check implementation is NFR and critical in many aspects of the application life cycle development. It allows you to monitor real-time information on the health of various resources, databases, services your business application is dependent on.

This ultimately helps you in troubleshooting, resolving technical or environmental issues easily.

Today in this article, we will cover below aspects,

In ASP.Net core Health check services and health check middleware provides us capabilities to validate API by letting you add health check route, Additionally, it also lets you validate the health of external resources like external service connection external database, etc.

Example: SQL Server database

These simple and easy-to-use feature lets you check the status of your resources and dependencies.

Getting started

If you already have an API, then please follow below two steps,

Step 1 – Register HealthCheck Service in ConfigureServices

Let’s register the Health check service in the API as below. Add AddHealthChecks in ConfigureServices method,.

Please add the below line of code in the ConfigureServices() method,

public void ConfigureServices(IServiceCollection services)
         {
             services.AddControllers();
             services.AddScoped();
             services.AddHealthChecks();
             services.AddHttpContextAccessor();
         }

Step 2 – Add Health Check endpoint middleware

Enable Health Check endpoint middleware in the API pipeline as below,

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
          
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHealthChecks("/health");
            });
        }

Verify health check endpoint

Let’s execute the HealthCheck endpoint,

Status: Healthy

Health Check in ASPNET Core using IhealthCheck

Status: UnHealthy

Below status shows unhealthy status for similar health check used for EfCore database availability.

Health Check in ASPNET Core Application

Create Custom health checks using IHealthCheck interface

The above-discussed health check works fine for standalone API. If your API had a dependency on other services or databases then, you can use a custom health check approach.

Step1 – Implement the IHealthCheck interface

Here please implement the IHealthCheck interface and override the CheckHealthAsync method.

public class CustomHealthCheck : IHealthCheck
    {
        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
         
            var healthCheckResultHealthy = await CheckSQLDBConnectionAsync();


            if (healthCheckResultHealthy)
            {
                return HealthCheckResult.Healthy("SQL health check success");
            }

            return HealthCheckResult.Unhealthy("SQL health check failure"); ;
        }

..

     }

 

HealthCheckResult lets you return health as HealthyDegraded, or Unhealthy

Step2 – Register health check services

In Startup.ConfigureServices please add the HealthChecks as below,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddScoped<IEmployeeRepository, EmployeeRepository>();
            services.AddHttpContextAccessor();
            services.AddHealthChecks()
                .AddCheck<CustomHealthCheck>("SQLDBConnectionCheck");
        }

That’s All, Enjoy Coding !!

Please sound off your comments below if any.

References:

Summary

A health check is critical in multiple aspects and allows you to check the health of various resources, databases, services your application is dependent on.

Today in this article we learned how to configure basic Health Check in the ASP.NET Core c# application.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *