C#C
C#3y ago
júlio

❔ IHealthCheck and Swagger

Hello. I'm experimenting with the interface IHealthCheck in my Web Service.
I used to have a endpoint that would just return 200OK called /health, but I discovered that there was a Interface for this, and with many functionalities, so I want to try get it working.

I followed the documentation (https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-7.0) and it kinda works, except Swagger complains a lot.
This is what my Controller looks like (the health check part):

[Route("api/[controller]")]
[ApiController]
public class PostalController : ControllerBase, IHealthCheck
{
  //...
  public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
  {
    var isHealthy = true;

    // ...

    if (isHealthy) 
    {
        return Task.FromResult(HealthCheckResult.Healthy());
    }

    return Task.FromResult(
        new HealthCheckResult(context.Registration.FailureStatus));
  }
}    

In Program.cs I have the following code:

builder.Services.AddHealthChecks().AddCheck<PostalController>("Postal Health Check");

//...
app.MapHealthChecks("/healthz", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions 
{ 
    AllowCachingResponses = false,
    ResultStatusCodes =
    {
        [HealthStatus.Healthy] = StatusCodes.Status200OK,
        [HealthStatus.Degraded] = StatusCodes.Status200OK,
        [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
    }
});


When I run the program, I get this message from Swagger: (attached image)
image.png
Was this page helpful?