I've added Microsoft.AspNetCore.Diagnostics.HealthChecks
style health checks to my application as documented by Microsoft here.
I am also using Swashbuckle to generate a swagger document. I then use NSwag to generate a client API for my other applications to use.
The problem is that the healthcheck endpoint added with MapHealthChecks
in Startup.cs is not being added to the ApiExplorer
. This is a problem, because it is what Swashbuckle uses to generate the swagger document.
So my question what is the best way to add the healthcheck endpoint to ApiExplorer so that Swashbuckle can include it in the swagger file?
I have attempted to manually add the health check endpoint add ApiExplorer (code below). The application ran successfully, but the swagger document did not contain the endpoint.
// from Startup.cs
public virtual void ConfigureServices(IServiceCollection services)
{
// ...
// add swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
// add healthchecks
services
.AddHealthChecks()
.AddDbContextCheck<DatabaseDomain.DbContext>(tags: new[] { "db" })
;
// ...
}
public virtual void Configure(IApplicationBuilder app, IHostEnvironment env, IApiDescriptionGroupCollectionProvider apiExplorer)
{
// ...
app.UseEndpoints(endpoints =>
{
endpoints.
.MapHealthChecks("/healthcheck", new HealthCheckOptions
{
Predicate = _ => true, // allow all healthchecks
AllowCachingResponses = false,
// custom writer to return health check results as JSON
ResponseWriter = (context, result) => {
context.Response.ContentType = "application/json";
// serialize the health check results
var json = System.Text.Json.JsonSerializer.Serialize(new
{
// my custom response object
});
return context.Response.WriteAsync(json);
},
})
.RequireAuthorization()
;
});
// attempt to get the healthcheck endpoint to ApiExplorer
var healthcheckDescription = new ApiDescription
{
HttpMethod = "GET",
RelativePath = "/healthcheck",
};
healthcheckDescription.SupportedRequestFormats.Add(new ApiRequestFormat
{
MediaType = "application/json"
});
healthcheckDescription.SupportedResponseTypes.Add(new ApiResponseType
{
IsDefaultResponse = true,
StatusCode = (int)HttpStatusCode.OK,
ApiResponseFormats = new List<ApiResponseFormat> {
new ApiResponseFormat
{
MediaType = "application/json"
}
}
});
apiExplorer.ApiDescriptionGroups.Items.Append(new ApiDescriptionGroup("HealthCheck", new List<ApiDescription> { healthcheckDescription }));
// configure swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
// ...
}