What is .Net HealthCheck, how is it done?

What is .Net HealthCheck, how is it done?


First of all, I want to talk about writing extension. You can extend any existing object or variable type in dotnet with helper methods like .ToString() as in string variables. I recommend you to research how to write .net extension related to the subject. Let's continue for those who know..

We are constantly making configurations at Startup.cs. If you notice over time, there is a code confusion in Startup.cs and it looks very ugly. Therefore, we will focus on our work by using the extension for IServiceCollection and IApplicationBuilder.

Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore

AspNetCore.HealthChecks.UI

AspNetCore.HealthChecks.UI.InMemory.Storage

AspNetCore.HealthChecks.UI.Client

After installing the packages, let's create our class below.

public static class PcHealthCheckExtension
{
    public static void PcAddHealthCheck(this IServiceCollection services)
    {
        services.AddHealthChecks()
            .AddDbContextCheck<YourDbContext>();

        services.AddHealthChecksUI()
            .AddInMemoryStorage(); 
    }

    public static IApplicationBuilder PcUseHealthCheck(this IApplicationBuilder app)
    {
        app.UseHealthChecks("/healthcheck", new HealthCheckOptions
        {
            Predicate = _ => true,
            ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
        });

        app.UseHealthChecksUI(options =>
        {
            options.UIPath = "/healthchecks";
            options.ApiPath = "/healthchecks-api";
        });
        return app;
    }
}

Our extensions and configurations are complete. Now let's introduce this to your project and activate it. You can enable the following in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    services.PcAddHealthCheck();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.PcUseHealthCheck();
}

Finally, let's add the following to appsettings.json for the configuration settings of the library.

{
  "HealthChecks-UI": {
    "DisableMigrations": true,
    "HealthChecks": [
      {
        "Name": "PollManager",
        "Uri": "/healthcheck"
      }
    ],
    "Webhooks": [
      {
        "Name": "",
        "Uri": "",
        "Payload": "",
        "RestoredPayload": ""
      }
    ],
    "EvaluationTimeOnSeconds": 10,
    "MinimumSecondsBetweenFailureNotifications": 60,
    "MaximumExecutionHistoriesPerEndpoint": 15
  }
}

Our code looks clean and tidy. When you run our project and go to "/healthchecks" "/healthchecks-api", you will see the result.

An error has occurred. This application may no longer respond until reloaded. Reload 🗙