Easy ASP.NET Core Health Check

Getting emails after something went wrong in your production running code is now these days thing of the past. I mean not get me wrong I did use email notifications a long time ago (when Jr.) then I moved into Loggers such as NLog and Serilog, however despite there robust documentation not many developers adventures to use such tools. Health check for ASP.NET Core adds even more monitoring down to check services and/or databases to render if your application is Health or not and that it’s powerful. Now, you have a way to be more proactive about monitoring your app and acting in a pro-active way. Fixing error before the customer realized or complains about it.

Health checks are exposed by an app as HTTP endpoints.

Some of the scenarios one may want to monitor are:

  • Check health of Disk, Memory and/or other server resources.
  • Check health of app’s databases, dependencies such as external services
  • Health check can be use with an container orchestrator and load balancers to respond to failing apps and deploy new instance or to restart a container.

ASP.NET Core Health Check are configure within the Startup.cs file, which implicitly refers package Microsoft.AspNetCore.Diagnostics.HealthChecks from ASP.NET Core apps.

Out of the box implementation

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add this line
        services.AddHealthChecks();
 
        //....
        // other services configs
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
             endpoints.MapControllers();
             // name it as you wish             
             endpoints.MapHealthChecks("/health");
 
             
        });
    }
}

Now, that the basic example is out of the way let’s get a bit more custom.

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health", new HealthCheckOptions()
    {
        ResultStatusCodes =
        {
            [HealthStatus.Healthy] = StatusCodes.Status200OK,
            [HealthStatus.Degraded] = StatusCodes.Status200OK,
            [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
        }
    });
});

You may have the need to customized the result of the health check which can be done as it’s shown in the example above. HealthStatus.Health will return an HTTP 200, HealthStatus.Degraded will also return a 200 – OK, and lastly HealthStatus.Unhealthy will return an HTTP 503 – Service Unavailable.

There you have it a very simple way to add health check to your ASP.NET Core app.

References:
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1

Spread the word
  • Yum