Advertisement
Intermediate ASP.NET Core, Health Checks

How do you customize the JSON response format of the health check endpoint, since the default output is just plain text status?

Short answer

The default MapHealthChecks() endpoint returns only plain text ("Healthy", "Unhealthy"), but you can supply a custom ResponseWriter delegate in HealthCheckOptions to produce a structured JSON response including each individual check's name, status, duration, and description --…

Save ASP.NET Core mock interview
Advertisement
AModel answer
The default MapHealthChecks() endpoint returns only plain text ("Healthy", "Unhealthy"), but you can supply a custom ResponseWriter delegate in HealthCheckOptions to produce a structured JSON response including each individual check's name, status, duration, and description -- valuable for monitoring dashboards or debugging which specific dependency is causing an overall Unhealthy status.
app.MapHealthChecks("/health", new HealthCheckOptions {
    ResponseWriter = async (context, report) => {
        context.Response.ContentType = "application/json";
        var result = JsonSerializer.Serialize(new {
            status = report.Status.ToString(),
            checks = report.Entries.Select(e => new { name = e.Key, status = e.Value.Status.ToString(), duration = e.Value.Duration.TotalMilliseconds })
        });
        await context.Response.WriteAsync(result);
    }
});
Real-world example
A monitoring dashboard consumes a custom JSON-formatted /health response showing each individual dependency's status and response time, letting operators immediately identify that it's specifically the Redis cache check failing rather than just knowing the overall status is Unhealthy.
Likely follow-ups
  • How would you use the AspNetCore.HealthChecks.UI package instead of writing a custom formatter from scratch?
  • Should the detailed health check response be exposed publicly, or restricted to internal monitoring systems only?
Related topics