I am using Dotnet Core healthchecks as described here. In short, it looks like this:
First, you configure services like this:
services.AddHealthChecks()
.AddSqlServer("connectionString", name: "SQlServerHealthCheck")
... // Add multiple other checks
Then, you register an endpoint like this:
app.UseHealthChecks("/my/healthCheck/endpoint");
We are also using Swagger (aka Open API) and we see all the endpoints via Swagger UI, but not the health check endpoint.
Is there a way to add this to a controller method so that Swagger picks up the endpoint automatically, or maybe integrate it with swagger in another way?
The best solution I found so far is to add a custom hardcoded endpoint (like described here), but it is not nice to maintain.
Still looking for a better solution, but a poor man's solution to this problem looks like this:
public const string HealthCheckEndpoint = "/my/healthCheck/endpoint";
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
var pathItem = new PathItem();
pathItem.Get = new Operation()
{
Tags = new[] { "ApiHealth" },
Produces = new[] { "application/json" }
};
var properties = new Dictionary<string, Schema>();
properties.Add("status", new Schema(){ Type = "string" });
properties.Add("errors", new Schema(){ Type = "array" });
var exampleObject = new { status = "Healthy", errors = new List<string>()};
pathItem.Get.Responses = new Dictionary<string, Response>();
pathItem.Get.Responses.Add("200", new Response() {
Description = "OK",
Schema = new Schema() {
Properties = properties,
Example = exampleObject }});
swaggerDoc.Paths.Add(HealthCheckEndpoint, pathItem);
}