Custom ASP.NET Core Health Check Response

In my previous post I went over how to implement the out of the box Health check capabilities, we find in dotnet core. Now, I would like to show you how to customize a health check response in ASP.NET Core.

Let’s jump right into it.

public class HealthCheckResponseExample
    public static Task HealthCheckResponseWriter(HttpContext context, HealthReport healthReport)
            context.Response.ContentType = "application/json";
            var result = JsonConvert.SerializeObject(new
                overall = healthReport.Status.ToString(),
                checks = healthReport.Entries.Select(e => new
                    name = e.Key,
                    status = e.Value.Status.ToString(),
                    message = e.Value.Description,
                    exception = e.Value.Exception?.Message,
                    duration = e.Value.Duration.ToString("c")
            return context.Response.WriteAsync(result);

The code above takes a HttpContext and a HealthReport object, the HealthReport object is the one we want because it contains the outcomes of the check dependencies.

This is how we consume in startup.cs

public void ConfigureServices(IServiceCollection services)
                    .AddSqlServer("db connection"), name: "SQL DB Check");

// some more code

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

            app.UseEndpoints(endpoints =>
                endpoints.MapHealthChecks("/health", new HealthCheckOptions()
                    ResponseWriter = HealthCheckResponseExample.HealthCheckResponseWriter

As you see above calling the method is very straight forward. As a result we get a 200 – OK with JSON

    "overall": "Healthy",
    "checks": [
            "name": "SQL DB Check",
            "status": "Healthy",
            "message": null,
            "exception": null,
            "duration": "00:00:01.3147942"

Some extra NuGets are necessary if you are checking on DBs, but if you only are checking for MSQL Server you can add the NuGet package AspNetCore.HealthChecks.SqlServer , if you are using a different database you may want to search for the package for that database.

In conclusion, adding a custom response is very easy and you may want to add some other pieces of information based on your needs.


Spread the word
  • Yum