Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 21 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,40 +70,33 @@ app.MapSimpleHealthPage("/health-ui", options =>

This is the same `Func<HealthCheckRegistration, bool>` shape as `HealthCheckOptions.Predicate` used by `MapHealthChecks`.

## Example for dynamic response
## Plain text output

If you want a single entry URL, you can dispatch based on the Accept header:
Browsers typically include `text/html` on page navigation, so interactive users will see the UI automatically.

- `/health` with `Accept: text/html` -> MiniUI endpoint (`/health-ui`)
- `/health` with other Accept values -> machine endpoint (`/healthz`)
Opt in with `EnablePlainText` to serve a `text/plain` rendering to clients that do not accept `text/html`, such as `curl` or a container health check. Browsers still get the HTML page.

```csharp
// Custom Middleware for Accept header based routing
app.Use(async (context, next) =>
app.MapSimpleHealthPage("/health-ui", options =>
{
if (context.Request.Path == "/health")
{
var accept = context.Request.Headers.Accept.ToString();
var wantsHtml = accept.Contains("text/html", StringComparison.OrdinalIgnoreCase);

// Internal server-side rewrite for this request (no 3xx redirect to the client).
context.Request.Path = wantsHtml ? "/health-ui" : "/healthz";
}

await next();
options.EnablePlainText = true;
});
```

// Required in this setup so endpoint routing sees the rewritten /health path.
app.UseRouting();
```console
$ curl http://localhost:5000/health-ui
Health Checks
Status: Unhealthy
Duration: 1002.67 ms
Generated: 2026-09-05 09:12:33Z

| NAME | STATUS | DESCRIPTION | DURATION |
|---------|-----------|----------------------|------------|
| db | Healthy | connection ok | 1.5 ms |
| failing | Unhealthy | queue backlog too... | 1002.67 ms |
```

app.MapHealthChecks("/healthz");
Descriptions are shortened with `...` so the table stays readable in a terminal.

app.MapSimpleHealthPage("/health-ui", options =>
{
options.Title = "My App Health";
});
```
Combine it with `StatusCodes.Unhealthy` so `curl --fail` works.

## Demo app

Expand All @@ -117,9 +110,8 @@ dotnet run --project demo/HealthChecks.MiniUI.Demo/HealthChecks.MiniUI.Demo.cspr

Then open:

- `/health` as the dynamic entry URL (UI for browser requests, machine response for non-HTML Accept headers)
- `/health-ui` for the UI endpoint directly
- `/healthz` for the machine endpoint directly
- `/health-ui` for the UI (HTML in a browser, plain text for `curl`)
- `/healthz` for the machine endpoint

## Notes

Expand Down
20 changes: 3 additions & 17 deletions demo/HealthChecks.MiniUI.Demo/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,29 +51,15 @@

var app = builder.Build();

app.Use(async (context, next) =>
{
if (context.Request.Path == "/health")
{
var accept = context.Request.Headers.Accept.ToString();
var wantsHtml = accept.Contains("text/html", StringComparison.OrdinalIgnoreCase);

// Internal server-side rewrite for this request (no 3xx redirect to the client).
context.Request.Path = wantsHtml ? "/health-ui" : "/healthz";
}

await next();
});

app.UseRouting();

app.MapGet("/", () => Results.Redirect("/health"));
app.MapGet("/", () => Results.Redirect("/health-ui"));

app.MapHealthChecks("/healthz");

app.MapSimpleHealthPage("/health-ui", options =>
{
options.Title = "HealthChecks MiniUI Demo";
options.EnablePlainText = true;
options.StatusCodes.Unhealthy = StatusCodes.Status503ServiceUnavailable;
});

app.Run();
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,38 @@ public static IEndpointConventionBuilder MapSimpleHealthPage(
var healthCheckService = context.RequestServices.GetRequiredService<HealthCheckService>();
var report = await healthCheckService.CheckHealthAsync(options.Predicate, context.RequestAborted);

var renderer = new SimpleHealthPageHtmlRenderer
{
Title = options.Title,
Report = report,
GeneratedAtUtc = DateTimeOffset.UtcNow
};
var generatedAtUtc = DateTimeOffset.UtcNow;
var usePlainText = options.EnablePlainText && !AcceptsHtml(context.Request);

var html = renderer.Render();
string body;
if (usePlainText)
{
body = new SimpleHealthPageTextRenderer
{
Title = options.Title,
Report = report,
GeneratedAtUtc = generatedAtUtc
}.Render();
}
else
{
body = new SimpleHealthPageHtmlRenderer
{
Title = options.Title,
Report = report,
GeneratedAtUtc = generatedAtUtc
}.Render();
}

context.Response.StatusCode = ResolveStatusCode(report.Status, options.StatusCodes);
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync(html, context.RequestAborted);
context.Response.ContentType = usePlainText ? "text/plain; charset=utf-8" : "text/html; charset=utf-8";

if (options.EnablePlainText)
{
context.Response.Headers.Vary = "Accept";
}

await context.Response.WriteAsync(body, context.RequestAborted);
});

if (!string.IsNullOrWhiteSpace(options.AuthorizationPolicy))
Expand All @@ -56,6 +76,30 @@ public static IEndpointConventionBuilder MapSimpleHealthPage(
return endpoint;
}

private static bool AcceptsHtml(HttpRequest request)
{
foreach (var accept in request.Headers.Accept)
{
if (accept is null)
{
continue;
}

foreach (var range in accept.Split(','))
{
var mediaType = range.Split(';')[0].Trim();

if (mediaType.Equals("text/html", StringComparison.OrdinalIgnoreCase) ||
mediaType.Equals("application/xhtml+xml", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}

return false;
}

internal static int ResolveStatusCode(HealthStatus status, SimpleHealthPageStatusCodesOptions statusCodes)
{
ArgumentNullException.ThrowIfNull(statusCodes);
Expand Down
6 changes: 6 additions & 0 deletions src/HealthChecks.MiniUI/SimpleHealthPageOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ public sealed class SimpleHealthPageOptions
/// </summary>
public string? AuthorizationPolicy { get; set; }

/// <summary>
/// Gets or sets a value indicating whether requests that do not accept <c>text/html</c>
/// (for example <c>curl</c>) receive a <c>text/plain</c> rendering instead of the HTML page.
/// </summary>
public bool EnablePlainText { get; set; }

/// <summary>
/// Gets the HTTP status code mapping used for the page response based on overall health status.
/// </summary>
Expand Down
99 changes: 99 additions & 0 deletions src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace HealthChecks.MiniUI;

internal sealed class SimpleHealthPageTextRenderer
{
private static readonly string[] Headers = ["NAME", "STATUS", "DESCRIPTION", "DURATION"];

// Keeps the whole table within a classic 80 column terminal for typical check names.
private const int MaxDescriptionWidth = 40;

public string Title { get; set; } = "Health Checks";

public HealthReport? Report { get; set; }

public DateTimeOffset GeneratedAtUtc { get; set; }

public string Render()
{
var report = Report ?? throw new InvalidOperationException("Report must be set before rendering.");

var builder = new StringBuilder();
builder.Append(Title).Append('\n');

AppendField(builder, "Status", report.Status.ToString());
AppendField(builder, "Duration", FormatDuration(report.TotalDuration));
AppendField(builder, "Generated", GeneratedAtUtc.ToString("u", CultureInfo.InvariantCulture));

if (report.Entries.Count == 0)
{
return builder.ToString();
}

var rows = report.Entries
.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase)
.Select(x => new[]
{
x.Key,
x.Value.Status.ToString(),
FormatDescription(x.Value.Description),
FormatDuration(x.Value.Duration)
})
.ToList();

var widths = Headers
.Select((header, i) => Math.Max(header.Length, rows.Max(r => r[i].Length)))
.ToArray();

builder.Append('\n');
AppendRow(builder, Headers, widths);
AppendRow(builder, widths.Select(w => new string('-', w)).ToArray(), widths, pad: '-');

foreach (var row in rows)
{
AppendRow(builder, row, widths);
}

return builder.ToString();
}

private static void AppendField(StringBuilder builder, string label, string value)
{
const int LabelWidth = 11; // "Generated:" plus a separating space
builder.Append((label + ':').PadRight(LabelWidth)).Append(value).Append('\n');
}

private static void AppendRow(StringBuilder builder, IReadOnlyList<string> cells, IReadOnlyList<int> widths, char pad = ' ')
{
builder.Append('|');

for (var i = 0; i < cells.Count; i++)
{
// The duration column is right-aligned so the numbers line up.
var cell = i == cells.Count - 1 ? cells[i].PadLeft(widths[i], pad) : cells[i].PadRight(widths[i], pad);
builder.Append(pad).Append(cell).Append(pad).Append('|');
}

builder.Append('\n');
}

private static string FormatDuration(TimeSpan duration) =>
duration.TotalMilliseconds.ToString("0.##", CultureInfo.InvariantCulture) + " ms";

private static string FormatDescription(string? description)
{
if (string.IsNullOrWhiteSpace(description))
{
return string.Empty;
}

var singleLine = string.Join(' ', description.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));

return singleLine.Length <= MaxDescriptionWidth
? singleLine
: string.Concat(singleLine.AsSpan(0, MaxDescriptionWidth - 3), "...");
}
}
Loading