Implementing Health Checks to Monitor Status and Health in ASP.NET Core

Implementing health checks in ASP.NET Core is a great way to monitor the status and health of your API services. Health checks allow you to periodically test the different components of your application and ensure they are functioning properly. Here's a complete example of how to implement health checks in an ASP.NET Core application.

Prerequisites

Before you begin, make sure you have a basic understanding of ASP.NET Core and a working ASP.NET Core project.

Create a new ASP.NET Core Project

Start by creating a new ASP.NET Core project if you don't have one already. You can do this using the command line or your preferred IDE.

Install the required NuGet packages

Open the project's .csproj file and add the following package references.

<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="3.1.12" />

Make sure to adjust the version number as per your project's compatibility.

Configure Health Checks

In your Startup.cs file, add the necessary configurations for health checks in the ConfigureServices method.

using Microsoft.AspNetCore.Diagnostics.HealthChecks;

Author:Sardar Mudassar Ali Khan
public void ConfigureServices(IServiceCollection services)
{

    services.AddHealthChecks();
}

Configure Health Checks Endpoints

In the Configure method of your Startup.cs file, configure endpoints for health checks.

using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

Author:Sardar Mudassar Ali Khan
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

    app.UseHealthChecks("/health", new HealthCheckOptions
    {
        ResponseWriter = async (context, report) =>
        {
            var result = JsonConvert.SerializeObject(
                new
                {
                    status = report.Status.ToString(),
                    errors = report.Entries.Select(e => new { key = e.Key, value = 
                    e.Value.Status.ToString() })
                });
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(result);
        }
    });
}

In this example, the health check endpoint is configured at /health, and the response format is JSON. You can customize the response format as needed.

Adding Custom Health Checks

You can add your own custom health checks by implementing the IHealthCheck interface. For example, if you want to check the health of a database connection.

Author: Sardar Mudassar Ali Khan
public class DatabaseHealthCheck : IHealthCheck
{
    private readonly IDbConnection _dbConnection;

    public DatabaseHealthCheck(IDbConnection dbConnection)
    {
        _dbConnection = dbConnection;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        try
        {
            await _dbConnection.OpenAsync(cancellationToken);
            return HealthCheckResult.Healthy();
        }
        catch
        {
            return HealthCheckResult.Unhealthy();
        }
    }
}

Then, register this health check in the ConfigureServices method.

services.AddSingleton<IHealthCheck, DatabaseHealthCheck>();

Testing Health Checks

Start your ASP.NET Core application and navigate to /health in your browser or use tools like curl to see the health check results.

Conclusion

Implementing health checks in your ASP.NET Core API is a crucial aspect of ensuring the reliability and availability of your application. Health checks allow you to monitor the status and health of various components and dependencies within your system. By regularly checking the health of these components, you can proactively detect and address issues before they impact the user experience. Here's a summary of the key points covered in this example.

  • Importance of Health Check
    • Health checks provide real-time insights into the operational status of your application's components, such as databases, services, and external APIs. They help you maintain a higher level of reliability and better handle potential failures.
  • Setting Up Health Checks
    • Install the Microsoft.AspNetCore.Diagnostics.HealthChecks NuGet package.
    • Configure health checks in the ConfigureServices method using services.AddHealthChecks().
    • Configure a health check endpoint using the app.UseHealthChecks() in the Configure method.
  • Custom Health Checks
    • Implement custom health checks by creating classes that implement the IHealthCheck interface. This allows you to check the health of specific components or services that are critical to your application's functionality.
  • Response Formatting
    • Customize the health check response format to provide meaningful information about the health status of your application's components. In the provided example, the response is formatted as JSON.
  • Testing Health Checks
    • Test your health check implementation by navigating to the health check endpoint (e.g., /health) using a web browser, curl, or other HTTP tools. Review the JSON response to ensure that the health status of each component is accurately reported.

By incorporating health checks into your ASP.NET Core application, you can monitor its health, identify potential issues, and maintain a high standard of reliability for your users. Regularly reviewing and improving your health check setup will contribute to a smoother user experience and a more resilient application overall.


Similar Articles