ASP.NET Core  

How to Implement Health Checks in ASP.NET Core Applications

Introduction

In modern ASP.NET Core applications, especially when building scalable web APIs and microservices, monitoring the health of your application is extremely important. You need to know whether your application is running properly, whether the database is connected, and whether external services are available.

This is where Health Checks in ASP.NET Core come into play.

Health checks allow you to expose endpoints that report the status of your application. These endpoints can be used by load balancers, monitoring tools, and cloud platforms to ensure your application is healthy and ready to serve requests.

In this article, you will learn how to implement health checks in ASP.NET Core step by step using simple language, practical examples, and best practices. This guide is useful for developers working on .NET, ASP.NET Core Web API, microservices, and cloud-based applications.

What are Health Checks in ASP.NET Core?

Understanding Health Checks in Simple Words

Health checks are a way to verify whether different parts of your application are working correctly.

For example:

  • Is your API running?

  • Is your database connected?

  • Is your external service reachable?

Instead of manually checking these, health checks provide an automated way to monitor everything.

Why Health Checks are Important

  • Helps detect issues early

  • Improves application reliability

  • Supports auto-scaling in cloud platforms

  • Helps load balancers route traffic correctly

  • Useful for DevOps monitoring tools

Types of Health Checks

Liveness Check

This tells whether the application is running or not.

If this fails, the application is considered dead and needs to be restarted.

Readiness Check

This tells whether the application is ready to handle requests.

For example, if the database is down, the app may be running but not ready.

Custom Health Checks

These are user-defined checks like:

  • Database connectivity

  • API dependency check

  • Disk space check

Step 1: Create an ASP.NET Core Web API Project

You can create a new project using the .NET CLI:

dotnet new webapi -n HealthCheckDemo
cd HealthCheckDemo

Step 2: Add Health Check Services

Open Program.cs and register health check services:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Add Health Checks
builder.Services.AddHealthChecks();

var app = builder.Build();

app.UseHttpsRedirection();

// Map Health Check Endpoint
app.MapHealthChecks("/health");

app.MapControllers();

app.Run();

Now, when you run your application and navigate to /health, you will see the health status.

Step 3: Understanding Health Check Response

By default, the response will be simple:

  • Healthy → Application is working fine

  • Unhealthy → Something is wrong

You can customize this response later.

Step 4: Add Database Health Check

To check database connectivity, install the required package:

dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks.SqlServer

Then configure it:

builder.Services.AddHealthChecks()
    .AddSqlServer(
        connectionString: "your_connection_string",
        name: "SQL Server",
        timeout: TimeSpan.FromSeconds(5)
    );

This ensures your application checks if the database is reachable.

Step 5: Create Custom Health Check

Sometimes, you need custom logic.

Create a Custom Class

using Microsoft.Extensions.Diagnostics.HealthChecks;

public class CustomHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        bool isHealthy = true;

        if (isHealthy)
        {
            return Task.FromResult(HealthCheckResult.Healthy("Service is working"));
        }

        return Task.FromResult(HealthCheckResult.Unhealthy("Service is down"));
    }
}

Register Custom Health Check

builder.Services.AddHealthChecks()
    .AddCheck<CustomHealthCheck>("Custom Check");

Step 6: Customize Health Check Response

You can return detailed JSON instead of plain text.

app.MapHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = async (context, report) =>
    {
        context.Response.ContentType = "application/json";

        var result = System.Text.Json.JsonSerializer.Serialize(new
        {
            status = report.Status.ToString(),
            checks = report.Entries.Select(e => new
            {
                name = e.Key,
                status = e.Value.Status.ToString(),
                description = e.Value.Description
            })
        });

        await context.Response.WriteAsync(result);
    }
});

Now you get a detailed health report in JSON format.

Step 7: Tagging Health Checks (Liveness vs Readiness)

You can separate endpoints like this:

builder.Services.AddHealthChecks()
    .AddCheck("Liveness", () => HealthCheckResult.Healthy(), tags: new[] { "live" })
    .AddSqlServer("your_connection_string", tags: new[] { "ready" });

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("live")
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

This is very useful in Kubernetes and cloud environments.

Step 8: Integrating with Monitoring Tools

Health checks can be integrated with:

  • Azure Monitor

  • AWS CloudWatch

  • Kubernetes probes

  • Load balancers

These tools automatically monitor your endpoints and take action if something fails.

Step 9: Best Practices for Health Checks

Follow These Best Practices

  • Keep checks lightweight and fast

  • Avoid heavy database queries

  • Use timeouts

  • Separate liveness and readiness

  • Secure health endpoints if needed

Real-World Example

In an e-commerce application:

  • /health/live → Checks if API is running

  • /health/ready → Checks database and services

If database fails, traffic is stopped automatically.

Summary

Health checks in ASP.NET Core provide a powerful way to monitor application health, including database connectivity, external services, and system readiness. By using built-in middleware, custom health checks, and proper endpoint configuration, developers can build reliable, scalable, and cloud-ready .NET applications. Implementing health checks improves performance monitoring, reduces downtime, and ensures better user experience in modern web applications.