Are there advantages of using .NET Core's middleware "Health checks" over just a ping in a controller's route?

Viewed 491

I'm reading a "Asp.net Core 3 and Angular 9" book and there is an example usage of .NET Core Health check. It's also described on Microsoft website: https://docs.microsoft.com/en-US/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.0 I can't find a reason to actually use it over just creating a route in some controller which will ping external addresses.

Code in a book goes like this:

Add this in Configure (Startup.cs) method:

app.UseHealthChecks("/hc", new CustomHealthCheckOptions());

ConfigureServices method:

services.AddHealthChecks()
    .AddCheck("ICMP_01", new ICMPHealthCheck("www.ryadel.com", 100))
    .AddCheck("ICMP_02", new ICMPHealthCheck("www.google.com", 100))
    .AddCheck("ICMP_03", new ICMPHealthCheck("www.does-notexist.com", 100));

Create ICMPHealthCheck.cs file:

using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace HealthCheck
{
    public class ICMPHealthCheck : IHealthCheck
    {
        private string Host { get; set; }
        private int Timeout { get; set; }

        public ICMPHealthCheck(string host, int timeout)
        {
            Host = host;
            Timeout = timeout;
        }

        public async Task<HealthCheckResult> CheckHealthAsync(
            HealthCheckContext context,
            CancellationToken cancellationToken = default)
        {
            try
            {
                using (var ping = new Ping())
                {
                    var reply = await ping.SendPingAsync(Host);

                    switch (reply.Status)
                    {
                        case IPStatus.Success:
                            var msg = String.Format(
                                "IMCP to {0} took {1} ms.",
                                Host,
                                reply.RoundtripTime);

                            return (reply.RoundtripTime > Timeout)
                            ? HealthCheckResult.Degraded(msg)
                            : HealthCheckResult.Healthy(msg);
                        default:
                            var err = String.Format(
                                "IMCP to {0} failed: {1}",
                                Host,
                                reply.Status);

                            return HealthCheckResult.Unhealthy(err);
                    }
                }
            }
            catch (Exception e)
            {
                var err = String.Format(
                    "IMCP to {0} failed: {1}",
                    Host,
                    e.Message);
                return HealthCheckResult.Unhealthy(err);
            }
        }
    }
}

Create CustomHealthCheckOptions.cs file:

using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Net.Mime;
using System.Text.Json;
namespace HealthCheck
{
    public class CustomHealthCheckOptions : HealthCheckOptions
    {
        public CustomHealthCheckOptions() : base()
        {
            var jsonSerializerOptions = new JsonSerializerOptions()
            {
                WriteIndented = true
            };
            ResponseWriter = async (c, r) =>
            {
                c.Response.ContentType =
                MediaTypeNames.Application.Json;
                c.Response.StatusCode = StatusCodes.Status200OK;
                var result = JsonSerializer.Serialize(new
                {
                    checks = r.Entries.Select(e => new
                    {
                        name = e.Key,
                        responseTime = e.Value.Duration.TotalMilliseconds,
                        status = e.Value.Status.ToString(),
                        description = e.Value.Description
                    }),
                    totalStatus = r.Status,
                    totalResponseTime =
                    r.TotalDuration.TotalMilliseconds,
                }, jsonSerializerOptions);
                await c.Response.WriteAsync(result);
            };
        }
    }
}

So it just pings 3 addresses and I can't see advantages of using Microsoft.AspNetCore.Diagnostics.HealthChecks library. Is that wrong example?

0 Answers
Related