Skip to content

Add /health endpoint for container health checks #222

@nanotaboada

Description

@nanotaboada

Description

Introduce a standardized health check endpoint to expose the application’s health status for monitoring and orchestration purposes. This endpoint will:

  • Report overall application health and availability.
  • Validate critical subsystems (e.g., database connectivity).
  • Support liveness and readiness probes.
  • Provide a JSON payload with detailed health information.
  • Optionally integrate with a UI dashboard for visual monitoring.
  • Allow unauthenticated access for monitoring tools.

Suggested Approach

  1. Register health check services
    In Program.cs, add the health check services:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks();
  1. Map the health check endpoint
    Configure the middleware pipeline to expose /health:
var app = builder.Build();
app.MapHealthChecks("/health");
app.Run();
  1. Add dependency-specific checks
    Chain additional checks for critical dependencies:
builder.Services.AddHealthChecks()
    .AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"), name: "sql");
  1. Customize JSON response
    Use HealthCheckOptions.ResponseWriter to output a structured JSON payload:
app.MapHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = async (context, report) =>
        await CustomJsonResponseWriter(context, report)
});
  1. Enable anonymous access
    Update endpoint routing or authorization policies to allow unauthenticated probes on /health (per Steve Gordon’s pattern):
app.MapHealthChecks("/health").AllowAnonymous();
  1. (Optional) Integrate UI dashboard
    Add the UI viewer package and configure its endpoint for real‑time health metrics:
builder.Services.AddHealthChecksUI();
app.MapHealthChecksUI();

Acceptance Criteria

  • /health responds with HTTP 200 when all checks are Healthy, and HTTP 503 when any check is Degraded or Unhealthy.
  • Response includes structured JSON output with fields like status, totalDuration, and individual check details.
  • At least one dependency (e.g., SQL Server) is checked and reflected in the health response.
  • The /health endpoint is accessible without authentication.
  • Health check configuration is manageable via appsettings.json.
  • Automated tests validate Healthy, Degraded, and Unhealthy responses.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETPull requests that update .NET codeenhancementNew feature or requestgood first issueGood for newcomers

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions