Skip to content

Health checks in .netCore web APIs

Previously I have been writing health check controllers by hand. Now .netCore has a simple way of managing service health checks via middleware. You can test everything is operational all the way down to the database. You can even write your own custom checks in a few lines.

A simple service operational health check can be enabled by adding two lines to your startup.cs file. One in the services configuration and one in the application configuration.

public void ConfigureServices(IServiceCollection services)
{      
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddHealthChecks();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
            
    app.UseHealthChecks("/health");
    app.UseHttpsRedirection();
    app.UseMvc();
}

The “/health” parameter specifies the route to be used for the health check. When navigating to the route, a message will be displayed on success.

This will not check the health of any dependencies. This checks that the API can be reached, and is serving requests. You can include a basic database health check through the health check builder.

public void ConfigureServices(IServiceCollection services)
{      
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddHealthChecks()
       .AddSqlServer(Configuration["ConnectionStrings:DefaultConnection"]);
}

This will perform the same check as we did before, but it will also check that the database is operational and the connection is working. It does this by performing a simple “SELECT 1” query and checking for a successful result.

If you are using Entity Framework Core, you can check that the context is working correctly instead. Simply pass in your context.

public void ConfigureServices(IServiceCollection services)
{      
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
    services.AddHealthChecks()
       .AddDbContextCheck<AppDbContext>();

    services.AddDbContext<AppDbContext>(options =>
    {
        options.UseSqlServer(
            Configuration["ConnectionStrings:DefaultConnection"]);
    });
}

If this still isn’t enough you can write your own custom health checks. There are two ways of doing this. You can implement the IHealthCheck interface and register this class in the same way we registered the other checks. The implementation of the IHealthCheck CheckHealthAysnc method should return a task with a HealthCheckResult.

public void ConfigureServices(IServiceCollection services)
{      
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddHealthChecks()
       .AddCheck<MyHealthCheck>("my_health_check");
}

You can opt to write this as a lambda function directly as well.

public void ConfigureServices(IServiceCollection services)
{      
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddHealthChecks()
       .AddCheck("health check", () =>
            HealthCheckResult.Healthy("OK!"), tags: new[] { "health check" })
}

The health check above will always return healthy, but you could expand it with some conditions. For more information see the Microsoft docs.

Published inC#Web API

Comments are closed.