How do I call DotNet Core API HealthCheck probes within Controller instead of setting up in Ctartup.cs

756 views Asked by At

I would like to setup Microsoft.Extensions.Diagnostics.HealthChecks so that I can setup response body within controller instead of standard setup in Startup.cs. Is this possible? If so, how can I achieve this?

The thought here is that I would like control over the response payload setter logic, and to do this within a controller action/method.

Online contains clear instructions on how to setup healthcheck probes, but all examples show the setup occuring within Startup.cs.

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1

Are probes strickly setup within startup only? Is this a constraint?

My understanding is that the healtcheck library is middleware that will terminate request from going further down the middleware pipeline, and that perhaps removing the middleware will mean that whatever was setup in startup must now be setup within controller action method.

2

There are 2 answers

2
Derviş Kayımbaşıoğlu On

Is it possible to setup healthcheck probes within controller action methods? Answer is No

You can use app.UseHealthChecks to have custom control on health check enpoint

app.UseHealthChecks("/health-detailed", new HealthCheckOptions
        {
            ResponseWriter = (context, result) =>
            {
                context.Response.ContentType = "application/json";
                
                var json = new JObject(
                    new JProperty("status", result.Status.ToString()),
                    new JProperty("duration", result.TotalDuration),
                    new JProperty("results", new JObject(result.Entries.Select(pair =>
                        new JProperty(pair.Key, new JObject(
                            new JProperty("status", pair.Value.Status.ToString()),
                            new JProperty("tags", new JArray(pair.Value.Tags)),
                            new JProperty("description", pair.Value.Description),
                            new JProperty("duration", pair.Value.Duration),
                            new JProperty("data", new JObject(pair.Value.Data.Select(
                                p => new JProperty(p.Key, p.Value))))))))));
                context.Response.ContentType = MediaTypeNames.Application.Json;
                return context.Response.WriteAsync(
                    json.ToString(Formatting.Indented));
            }
        });
1
FlyingV On

TL&DR: Use this Library: https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks if you want somthing already created.

This website provides a ton of fully functional healthchecks for different services such as PostGres, Redis, S3, and etc.