Your ASP.NET Core 10 parking-sensor API needs detailed health JSON for operators but a minimal answer for the internet; how do you restrict and shape the endpoints?
answer
- minimal public, detailed private
- custom ResponseWriter for JSON
- RequireHost matches the Host header
- UseHealthChecks port checks LocalPort
- RequireAuthorization or AllowAnonymous
basics
~20 sKeep the probe endpoints on the default minimal writer, and map a separate detailed endpoint with a JSON ResponseWriter, restricted by RequireHost on a management port plus RequireAuthorization, since the Host header can be spoofed.
solid answer
~40 sThe default writer only prints `Healthy`, `Degraded` or `Unhealthy`, which is safe to expose to probes. For operators I map a second endpoint, `/health/details`, with a `ResponseWriter` that serialises `HealthReport.Entries` to JSON: name, status, duration and description. Descriptions can contain exception messages, so that endpoint must not be public. `RequireHost("*:8081")` limits it to a management port, but host matching reads the `Host` header, which a client controls, so I add `RequireAuthorization(...)` as the real gate. `UseHealthChecks(path, port)` filters on the connection's local port instead, which a header cannot fake. If the app has an authorization fallback policy, the probe endpoints need `.AllowAnonymous()` or the probes get 401. `ResultStatusCodes` can remap statuses but must include all three.
code
csharp · 24 linesusing Microsoft.AspNetCore.Diagnostics.HealthChecks;
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("ready")
}).AllowAnonymous();
app.MapHealthChecks("/health/details", new HealthCheckOptions
{
ResponseWriter = (ctx, report) => ctx.Response.WriteAsJsonAsync(new
{
status = report.Status.ToString(),
totalMs = report.TotalDuration.TotalMilliseconds,
checks = report.Entries.Select(e => new
{
name = e.Key,
status = e.Value.Status.ToString(),
ms = e.Value.Duration.TotalMilliseconds,
description = e.Value.Description
})
})
})
.RequireHost("*:8081")
.RequireAuthorization("HealthOps");go deeper
Know that the default health response only says Healthy, Degraded or Unhealthy, and that detailed output needs a custom ResponseWriter.
Build a JSON ResponseWriter from HealthReport entries, and explain ResultStatusCodes validation and the default no-cache headers.
Separate public probes from a detailed endpoint, explain why RequireHost is spoofable while UseHealthChecks' port filter is not, and add AllowAnonymous when a fallback policy exists.
Set the organisation's rule for what health output may leave the cluster, and how management ports and operator access are provisioned consistently.
## Two audiences, two endpoints The parking-sensor API is called by two very different clients: - **Probes and load balancers** need a status code and nothing else. They often reach the pod over the same port as public traffic. - **Operators** want to know *which* check failed, how long each took and why. Serving both from one endpoint forces a bad trade: either operators get nothing, or the internet gets your dependency list and error messages. The usual answer is two mappings over the same registrations. ## Shaping the response `HealthCheckOptions.ResponseWriter` is a `Func<HttpContext, HealthReport, Task>`: - The default, `WriteMinimalPlaintext`, sets `text/plain` and writes only the overall status word. It never includes names, descriptions or exceptions. - A custom writer can serialise `HealthReport.Status`, `TotalDuration` and each `HealthReportEntry`'s `Status`, `Duration`, `Description` and `Data`, for example with `HttpResponse.WriteAsJsonAsync`. - Be careful with `Description` and `Exception`: when a check throws, the service stores the exception's message as the description, and database drivers' messages can name hosts, databases or users. Never serialise `Exception` itself. Other response options: 1. **`ResultStatusCodes`**: remaps `HealthStatus` to HTTP codes. Assigning a dictionary that lacks any of the three statuses throws `InvalidOperationException`; it does not fall back for the missing key. 2. **`AllowCachingResponses`**: `false` by default, which adds `Cache-Control: no-store, no-cache`, `Pragma: no-cache` and a past `Expires`. ## Writing the JSON writer safely - `WriteAsJsonAsync` sets `application/json; charset=utf-8` and uses the app's configured `System.Text.Json` options, so the writer stays a one-liner. - Convert `HealthStatus` values with `ToString()` (or configure a string enum converter); otherwise they serialise as the numbers 0, 1 and 2. - Project to an anonymous type or a small record instead of serialising `HealthReportEntry` directly, which would include the `Exception` object. - The status code is already set before the writer runs, so the writer should not change it. - Keep `Data` values simple numbers and strings; they are what dashboards and humans read. ## Restricting who can call the detailed endpoint | Mechanism | What it checks | Spoofable by the client? | |---|---|---| | `MapHealthChecks(...).RequireHost("*:8081")` | the request's `Host` header (host and port) | yes, the header is client-supplied | | `app.UseHealthChecks("/health/details", 8081)` | `HttpContext.Connection.LocalPort` | no, it is the socket Kestrel accepted on | | `MapHealthChecks(...).RequireAuthorization("HealthOps")` | an authenticated user meeting a policy | no, if authentication is sound | The ASP.NET Core docs themselves warn that `RequireHost` can be spoofed and recommend adding `RequireAuthorization`. A local-port filter is only meaningful when Kestrel actually listens on that second port and the port is not exposed publicly. What the `HealthOps` policy demands is an authorization question; the point here is that a policy is the gate and the host filter is routing. ## The opposite problem: probes getting 401 Apps that set an authorization **fallback policy** requiring authenticated users apply it to every endpoint without its own authorization metadata, health checks included. The kubelet or load balancer cannot log in, so the probes start failing with 401 and the platform marks every pod unhealthy. Mark the probe endpoints with **`.AllowAnonymous()`**. ## Putting it together 1. `/health/live` and `/health/ready`: default writer, `AllowAnonymous()`, tag predicates. 2. `/health/details`: all checks, JSON writer, `RequireHost("*:8081")` plus `RequireAuthorization("HealthOps")`. 3. Kestrel listens on 8080 for traffic and 8081 for management; only 8080 is exposed outside the cluster. ## Checks in the review - Does any public response include check names, descriptions or exception text? - Is any restriction relying on `RequireHost` alone? - Will a future fallback policy silently break the probes?
- Why is RequireHost("*:8081") alone not enough to keep the detailed endpoint private?Host matching compares the request's `Host` header, including its port, and the client writes that header. A caller reaching the public port can send `Host: anything:8081` and match. Put `RequireAuthorization` on the endpoint, or use `UseHealthChecks(path, port)`, which tests the connection's actual local port.
- You set ResultStatusCodes to a dictionary containing only Unhealthy -> 503. What happens?The setter validates the mapping and throws `InvalidOperationException` listing the missing `HealthStatus` values, so startup fails at the line that assigns it. Every status needs an entry, for example Healthy 200, Degraded 503, Unhealthy 503 when degraded instances should leave rotation.
- The default health endpoint writes each check's exception message to the response.
- RequireHost("*:8081") cannot be bypassed because the port comes from the socket.
- A health endpoint is never affected by the app's authorization fallback policy.
- ResultStatusCodes only needs entries for the statuses you want to change.
- AllowCachingResponses defaults to true, so proxies may cache health responses.