In ASP.NET Core 10, how do you expose a health endpoint with AddHealthChecks and MapHealthChecks, and what does it return?
answer
- one service call, one endpoint call
- IHealthChecksBuilder from AddHealthChecks
- text/plain Healthy, Degraded or Unhealthy
- 200, 200, 503 by default
- worst check wins
basics
~10 sCall builder.Services.AddHealthChecks() and app.MapHealthChecks("/healthz"). The endpoint runs every registered check and writes Healthy, Degraded or Unhealthy as plain text, with 200 for Healthy and Degraded and 503 for Unhealthy.
solid answer
~40 sTwo calls are enough. `builder.Services.AddHealthChecks()` registers the `HealthCheckService` and returns an `IHealthChecksBuilder` on which checks are added with `AddCheck`. `app.MapHealthChecks("/healthz")` maps an endpoint that runs the checks and turns the result into a response. The overall status is the worst individual status, and an app with no checks reports `Healthy`. The default writer sends `text/plain` with just the word `Healthy`, `Degraded` or `Unhealthy`, and the default status codes are 200 for `Healthy` and `Degraded` and 503 for `Unhealthy`. The response also carries `Cache-Control: no-store, no-cache` unless `AllowCachingResponses` is set. Because `MapHealthChecks` returns an `IEndpointConventionBuilder`, conventions such as `RequireHost` or `RequireAuthorization` chain onto it like any other endpoint.
code
csharp · 11 linesvar builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks(); // returns IHealthChecksBuilder
var app = builder.Build();
app.MapHealthChecks("/healthz"); // 200 Healthy | 200 Degraded | 503 Unhealthy
app.MapGet("/bays/free", () => Results.Ok(new[] { "A1", "B7" }));
app.Run();go deeper
Recall the two calls, AddHealthChecks and MapHealthChecks, and the default mapping: Healthy and Degraded give 200, Unhealthy gives 503, with a plain-text status word.
Explain the aggregate as the worst result, the no-cache headers, the HealthCheckOptions knobs, and why MapHealthChecks beats UseHealthChecks in an endpoint-routed app.
Decide what the default 200-on-Degraded means for your load balancer and remap ResultStatusCodes per endpoint when degraded instances must leave rotation.
Standardise health endpoint paths, status mapping and response detail across services so platform tooling can treat every service the same way.
## What a health endpoint is in ASP.NET Core A **health check endpoint** is an HTTP URL that an orchestrator, load balancer or monitoring system calls to ask "is this instance OK?". ASP.NET Core ships the building blocks in two layers: - **`Microsoft.Extensions.Diagnostics.HealthChecks`**: the `IHealthCheck` interface, `HealthCheckResult`, `HealthStatus`, and the `HealthCheckService` that runs registered checks. It is part of the ASP.NET Core shared framework. - **`Microsoft.AspNetCore.Diagnostics.HealthChecks`**: the HTTP side, `MapHealthChecks` and `HealthCheckOptions`, which turn a health report into a response. ## The minimal setup For a parking-sensor API that reports which bays are free: 1. **Register the service.** `builder.Services.AddHealthChecks()` registers `HealthCheckService` as a singleton and returns an **`IHealthChecksBuilder`**. Checks are chained on that builder (`AddCheck`, `AddCheck<T>`, `AddDbContextCheck<T>` and so on). 2. **Map the endpoint.** `app.MapHealthChecks("/healthz")` adds a routed endpoint. On each request it runs the checks and writes the response. With no checks registered the endpoint still answers: it reports `Healthy`, which is a useful "the process is up and serving HTTP" signal. ## What comes back | Overall status | Default HTTP status | Default body | |---|---|---| | `Healthy` | `200 OK` | `Healthy` | | `Degraded` | `200 OK` | `Degraded` | | `Unhealthy` | `503 Service Unavailable` | `Unhealthy` | Details worth knowing: - The body is **`text/plain`** and contains only the status word. Individual check names, descriptions and exceptions are **not** written by the default writer. - The overall status is the **worst** of the individual results; one `Unhealthy` check makes the whole report `Unhealthy`. - `HealthStatus` is ordered `Unhealthy = 0`, `Degraded = 1`, `Healthy = 2`, which is how "worst" is computed. - The response gets `Cache-Control: no-store, no-cache`, `Pragma: no-cache` and an `Expires` date in the past, so proxies do not serve a stale answer. `HealthCheckOptions.AllowCachingResponses = true` turns that off. - Checks run **concurrently**, so the endpoint's latency is roughly that of the slowest check. ## What happens inside one request When a probe calls `/healthz`, the endpoint runs `HealthCheckMiddleware`: 1. It calls `HealthCheckService.CheckHealthAsync(predicate, httpContext.RequestAborted)`. The predicate comes from the endpoint's options (`null` means "all checks"), and the request's abort token is passed through, so a probe that gives up cancels the checks. 2. The service runs each selected check in its own DI scope, concurrently, and builds a `HealthReport` whose `Status` is the worst entry. 3. The middleware looks up `report.Status` in `ResultStatusCodes` and sets the response status code. 4. Unless `AllowCachingResponses` is `true`, it adds the no-cache headers. 5. It calls the `ResponseWriter`, the plain-text writer by default. Nothing in this flow throws for an unhealthy result; a failing dependency becomes a 503, not an exception page. ## Interview traps at this level - **"Degraded fails the probe."** It does not by default; Degraded is 200. - **"No checks means no endpoint."** The endpoint answers `Healthy` with zero checks. - **"The body explains the failure."** The default body is a single word; diagnosis needs a custom writer or the logs, since the service logs each check's result. - **"AddHealthChecks maps the URL."** It only registers services; nothing is reachable until `MapHealthChecks` (or `UseHealthChecks`) runs. ## Customising the endpoint `MapHealthChecks` has an overload that takes `HealthCheckOptions`: - `Predicate` chooses which registered checks this endpoint runs, which is how separate liveness and readiness endpoints are built; - `ResultStatusCodes` remaps statuses to HTTP codes (every `HealthStatus` must have an entry); - `ResponseWriter` replaces the plain-text body, for example with JSON; - `AllowCachingResponses` controls the no-cache headers. Because `MapHealthChecks` returns an **`IEndpointConventionBuilder`**, endpoint conventions chain on it: `RequireHost` to answer only on a management port or `RequireAuthorization` to demand an authenticated caller. ## Endpoint routing versus the older middleware `app.UseHealthChecks("/healthz")` also exists. It adds a middleware branch that answers requests matching the path (with overloads that also filter on a port) and lets every other request continue down the pipeline. It predates endpoint routing; `MapHealthChecks` is the current form because it participates in routing, authorization and other endpoint conventions. ## A quick sanity test ```bash curl -i http://localhost:5000/healthz ``` Expect `HTTP/1.1 200 OK`, `Content-Type: text/plain` and the body `Healthy`. Stop the database a readiness check depends on and the same call returns `503` with `Unhealthy`. ## What this does not decide Which path an orchestrator should probe, how often, and what it does on failure are platform concerns. ASP.NET Core's job is to run the checks you registered and report the result faithfully.
- Your only registered check returns Degraded. What does a load balancer that treats non-2xx as failure see?It sees `200 OK` with the body `Degraded`, because the default `ResultStatusCodes` map `Degraded` to 200. The instance stays in rotation. If degraded instances should be taken out, remap `Degraded` to 503 in `HealthCheckOptions.ResultStatusCodes` on that endpoint.
- Why might MapHealthChecks be preferred over UseHealthChecks in a .NET 10 app?`MapHealthChecks` creates a routed endpoint, so endpoint conventions apply: `RequireHost`, `RequireAuthorization` and `AllowAnonymous`. `UseHealthChecks` is a middleware branch matched by path and optional port, outside routing, so it does not take endpoint metadata and its place in the pipeline must be managed by hand.
- A Degraded result makes the default health endpoint return 503.
- MapHealthChecks returns JSON listing every check and its exception by default.
- An app with no registered checks makes MapHealthChecks return 404 or 503.
- The overall status is the average of the individual check results.
- Health checks only work with the older app.UseHealthChecks middleware.