Home > front end >  How to add Health Checks to Swagger
How to add Health Checks to Swagger

Time:05-06

after looking through many articles and not finding a clear answer, I would like to start one more time a topic about adding Health Checks to the swagger in ASP .Net Core.

Firstly, I would like to ask you if it is good idea to do that and how to do it in the easiest way.

Thanks in advance for all answers.

CodePudding user response:

First question, Why do we need Health Check?

When we create Health Checks, we can create very granular, specific checks for certain services, which helps us greatly when diagnosing issues with our application infrastructure, as we can easily see which service/dependency is performing poorly. Our application may still be up and running, but in a degraded state that we can’t easily see by simply using the application, so having Health Checks in place give us a better understanding of what a healthy state of our application looks like.

Instead of relying on our users reporting an issue with the application, we can monitor our application health constantly and be proactive in understanding where our application isn’t functioning correctly and make adjustments as needed.

Here is simple demo about database Health check

First, Write a controller and Inject HealthCheckService in it.

[Route("[controller]")]
    [ApiController]
    [AllowAnonymous]
    public class HealthController : ControllerBase
    {
        private readonly HealthCheckService healthCheckService;

        public HealthController(HealthCheckService healthCheckService)
        {
            this.healthCheckService = healthCheckService;
        }

        [HttpGet]
        public async Task<ActionResult> Get()
        {
            HealthReport report = await this.healthCheckService.CheckHealthAsync();
            var result = new
            {
                status = report.Status.ToString(),
                errors = report.Entries.Select(e => new { name = e.Key, status = e.Value.Status.ToString(), description = e.Value.Description.ToString() })
            };
            return report.Status == HealthStatus.Healthy ? this.Ok(result) : this.StatusCode((int)HttpStatusCode.ServiceUnavailable, result);
        }
    }

Then, In Program.cs(.Net 6), Configure the health check to test whether the query function of the database is normal

    //.....
    string connectionString = builder.Configuration.GetConnectionString("default");
    
    builder.Services.AddHealthChecks().AddCheck("sql", () =>
    {
        string sqlHealthCheckDescription = "Tests that we can connect and select from the database.";

        string sqlHealthCheckUnHealthDescription = "There is something wrong in database.";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
    
                //You can specify the table to test or test other function in database

                SqlCommand command = new SqlCommand("SELECT TOP(1) id from dbo.students", connection);
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                //Log.Error(ex, "Exception in sql health check");
                return HealthCheckResult.Unhealthy(sqlHealthCheckUnHealthDescription );
            }
        }
    
        return HealthCheckResult.Healthy(sqlHealthCheckDescription);
    });

    //......

Result:

Swagger will expose this health check endpoint

enter image description here

When the query function works fine in database,It will return 200

enter image description here

When there is something wrong in database, It will return 503

enter image description here

  • Related