We added health checks to a .NET app so we can quickly verify whether the API is running and whether it can reach its PostgreSQL database. The final result is a /health endpoint that returns structured JSON.
First, we added the health check packages to the project:
dotnet add package AspNetCore.HealthChecks.NpgSql --version 9.0.0
dotnet add package AspNetCore.HealthChecks.UI.Client --version 9.0.0
AspNetCore.HealthChecks.NpgSql gives us a PostgreSQL-specific health check. AspNetCore.HealthChecks.UI.Client gives us a useful JSON response writer instead of the default plain-text response.
Next, we imported the health check types in Program.cs:
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
The app already loads its database connection string from configuration:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
We reused that same connection string for the health check so the API checks the same PostgreSQL database used by Entity Framework.
Then we registered health checks with the service container:
builder.Services.AddHealthChecks().AddNpgSql(connectionString);
This tells ASP.NET Core to include a PostgreSQL connectivity check as part of the appโs health status.
Finally, we mapped a health endpoint after building the app:
app.MapHealthChecks("/health", new HealthCheckOptions { ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse });
Now the app exposes:
GET /health
When the app and database are healthy, the endpoint returns a JSON response showing the overall status and the PostgreSQL check result. If the database is unavailable or the connection string is wrong, the endpoint reports an unhealthy status.
Leave a Reply