ASP.NET Core provides health check middleware and libraries for reporting the health of application infrastructure components.
Health checks are exposed by the application as an HTTP endpoint. Health check endpoints can be configured for various real-time monitoring scenarios:

  • Health probes can be used by the container business process coordination and load balancer to check the status of the application. For example, the container business process coordinator can respond to a failed health check by stopping the rolling deployment or restarting the container. A load balancer can handle anomalous applications by routing traffic from a failed instance to a normal instance.
  • You can monitor the usage of memory, disks, and other physical server resources to see if they are in a healthy state.
  • Health checks can test application dependencies (such as databases and external service endpoints) to confirm availability and work.

This example shows the running state of the database where it validates the database connection and returns the corresponding result.

Copy        [Route("health")]
        public ActionResult Health()
        {
            using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true"))
            {
                try
                {
                    connection.Open();
                }
                catch (SqlException)
                {
                    return new StatusCodeResult(503);
               
                }
            }

            return new EmptyResult();
        }

When we request the address, if there is any connection problem when connecting to the database, it will display an empty message containing the 200 status code and the 503 status code.

Now based on these result status codes, we can monitor the system to take the relevant actions.

Starting with .NET Core 2.2, we don’t need to customize the check controller and interface for the running state, but the framework itself has provided us with a health check service.

Installation and operation

Install-Package Microsoft.Extensions.Diagnostics.HealthChecks

After installation, we need to add it in the ConfigureServices() and Configure() methods of the Startup.cs file.

Copy        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app
                .UseHealthChecks("/health");
         
        }


After we have configured the endpoints in the configure() method, we can request a view of the health of our application via /health .

But this is not enough for our previous needs, so how do we customize our health check?

Two ways to deal with

option 1

Copy        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks()
  .AddCheck("sql", () =>
  {

      using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true"))
      {
          try
          {
              connection.Open();
          }
          catch (SqlException)
          {
              return HealthCheckResult.Unhealthy();
          }
      }

      return HealthCheckResult.Healthy();

  });
        }

Here we use the anonymous method AddCheck() to write our custom validation logic. The result is the HealthCheckResult object, which contains 3 options.

  1. Healthy
  2. Unhealthy bad
  3. Degraded downgrade

option 2

Implement the IHealthCheck interface and implement the CheckHealthAsync() method as follows:

Copy   public class DatabaseHealthCheck : IHealthCheck
        {
            public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken =
             default)
            {
                using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true"))
                {
                    try
                    {
                        connection.Open();
                    }
                    catch (SqlException)
                    {
                        return  Task.FromResult(HealthCheckResult.Unhealthy());
                    }
                }

                return Task.FromResult(HealthCheckResult.Healthy());

            }
        }

After creating this class, we need to use some valid unique name, AddCheck The () method mentions this class in the ConfigureServices() method as shown below.

Copy     public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks()  
          .AddCheck<DatabaseHealthCheck>("sql");
        }

Now that our code is finished, we can add any number of Health Tasks as above, which will run in the order we declare here.

Custom status code

Before we also said that 200 is healthy and 503 is unhealthy, the Healthcheck service even provides a custom status code using its options object in the following way, giving us the ability to change this default status code.

Copyconfig.MapHealthChecks("/health", new HealthCheckOptions
                     {
                        ResultStatusCodes = new Dictionary<HealthStatus, int> { { HealthStatus.Unhealthy, 420 }, { HealthStatus.Healthy, 200 }, { HealthStatus.Degraded, 419 } }

                         
                     }); 

Custom output

We can customize the output to get clearer and more detailed information about each health check task. This is useful if we have multiple health check tasks to analyze which task makes the entire service health status “not normal.”

We can do this through the HealthCheckOptions ResponseWriter property.

Copy        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app
                 .UseRouting()
                 .UseEndpoints(config =>
                 {
                     config.MapHealthChecks("/health", new HealthCheckOptions
                     {
                        ResponseWriter=CustomResponseWriter
                        
                     }); 

                 });

        }
        private static Task CustomResponseWriter(HttpContext context, HealthReport healthReport)
        {
            context.Response.ContentType = "application/json";

            var result = JsonConvert.SerializeObject(new
            {
                status = healthReport.Status.ToString(),
                errors = healthReport.Entries.Select(e => new
                {
                    key = e.Key,
                    value = e.Value.Status.ToString()
                })
            });
            return context.Response.WriteAsync(result);

        }

Now we have json to display our detailed information and complete the check of health status.

Health check interface

Install-Package AspNetCore.HealthChecks.UI

After the installation is complete, you need to call the corresponding service method in the ConfigureServices() and Configure() methods accordingly.

Copypublic void ConfigureServices(IServiceCollection services)  
{  
    services.AddHealthChecksUI();  
}  
  
public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
{  
    app.UseHealthChecksUI();  
}  

Once the configuration is complete, you can run the application and point to the /healthchecks-ui address, which displays the following UI.

But the interface is not as we just customized, then we are configuring

Appsetting.json

Copy{
  "ApplicationInsights": {
    "InstrumentationKey": "your-instrumentation-key"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "HealthChecksUI": {
    "HealthChecks": [
      {
        "Name": "Test Health",
        "Uri": "https://localhost:44342/health"
      }
    ],
    "EvaluationTimeinSeconds": 10,
    "MinimumSecondsBetweenFailureNotifications": 60
  }
}

So you can see the health status.

Orignal link:https://www.cnblogs.com/yyfh/p/11787434.html