Implement Health-Check in Dot Net Core API and Integrate in Swagger

Veera Reddy
1 min readMar 1, 2021

Is the API Up ? Are the resources on which API is dependent on Up ?

These are the Questions answered by Health-Check Endpoint.

API uses recourses like DB, Folders/Storage, Queues, other API’s . . . We can create a Health-Check for each resource.

In StartUp.cs register hc’s as below -

//Register HealthChecks and UI

services.AddHealthChecks()

.AddCheck<SqlConnectionHealthCheck>(“API-db”)

.AddCheck<VendorApiHealthCheck>(“Api”)

.AddCheck<FolderHealthCheck>(“Folders”);

Implement these Health Checks — Each of this is a Class.

//Enable HealthChecks and UI

var options = new HealthCheckOptions();

options.ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse;

//app.UseHealthChecks(“/HealthCheck”, options);

app.UseEndpoints(endpoints => {

endpoints.MapHealthChecks(“/HealthCheck”, options);

});

Register Endpoint on Swagger UI —

Approach 1 — (Something I don’t like) — Create a HealthCheckController and Invoke the Health-Check.

Approach 2 — Register in Swagger UI as below

services.AddSwaggerGen(options => {

options.SwaggerDoc(“v1”, new OpenApiInfo { Title = “API Name”, Version = “v1” });

options.DocumentFilter<HealthChecksFilter>(); });

Create HealthChecksFilter Class -

public class HealthChecksFilter : IDocumentFilter

{

public const string HealthCheckEndpoint = @”/healthcheck”;

public void Apply(OpenApiDocument openApiDocument, DocumentFilterContext context)

{

var pathItem = new OpenApiPathItem();

var operation = new OpenApiOperation();

operation.Tags.Add(new OpenApiTag { Name = “ApiHealth” });

var properties = new Dictionary<string, OpenApiSchema>();

properties.Add(“status”, new OpenApiSchema() { Type = “string” });

properties.Add(“errors”, new OpenApiSchema() { Type = “array” });

var response = new OpenApiResponse();

response.Content.Add(“application/json”, new OpenApiMediaType

{ Schema = new OpenApiSchema {

Type = “object”,

AdditionalPropertiesAllowed = true,

Properties = properties,

} });

operation.Responses.Add(“200”, response);

pathItem.AddOperation(OperationType.Get, operation);

openApiDocument?.Paths.Add(HealthCheckEndpoint, pathItem);

} }

API Health-Check link should be visible now on Swagger UI.

--

--