From 0fc14dae1153690ac72978f97d040753c2a61dc1 Mon Sep 17 00:00:00 2001 From: gprossliner <6724584+gprossliner@users.noreply.github.com> Date: Sat, 5 Sep 2026 14:11:11 +0200 Subject: [PATCH 1/3] implemented base text rendering --- README.md | 26 +++ demo/HealthChecks.MiniUI.Demo/Program.cs | 2 + ...ealthPageEndpointRouteBuilderExtensions.cs | 62 ++++++- .../SimpleHealthPageOptions.cs | 6 + .../SimpleHealthPageTextRenderer.cs | 76 ++++++++ .../PlainTextTests.cs | 172 ++++++++++++++++++ 6 files changed, 335 insertions(+), 9 deletions(-) create mode 100644 src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs create mode 100644 tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs diff --git a/README.md b/README.md index 5dbd344..2052597 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,32 @@ app.MapSimpleHealthPage("/health-ui", options => This is the same `Func` shape as `HealthCheckOptions.Predicate` used by `MapHealthChecks`. +## Plain text output + +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 +app.MapSimpleHealthPage("/health-ui", options => +{ + options.EnablePlainText = true; +}); +``` + +```console +$ curl http://localhost:5000/health-ui +Health Checks +Status: Unhealthy +Duration: 1002.67 ms +Generated: 2026-09-05 09:12:33Z + +| NAME | STATUS | DURATION | +|---------|-----------|------------| +| db | Healthy | 1.5 ms | +| failing | Unhealthy | 1002.67 ms | +``` + +Combine it with `StatusCodes.Unhealthy` so `curl --fail` works without the Accept header routing shown below. + ## Example for dynamic response If you want a single entry URL, you can dispatch based on the Accept header: diff --git a/demo/HealthChecks.MiniUI.Demo/Program.cs b/demo/HealthChecks.MiniUI.Demo/Program.cs index 0a80bff..96c82fe 100644 --- a/demo/HealthChecks.MiniUI.Demo/Program.cs +++ b/demo/HealthChecks.MiniUI.Demo/Program.cs @@ -74,6 +74,8 @@ app.MapSimpleHealthPage("/health-ui", options => { options.Title = "HealthChecks MiniUI Demo"; + options.EnablePlainText = true; + options.StatusCodes.Unhealthy = StatusCodes.Status503ServiceUnavailable; }); app.Run(); diff --git a/src/HealthChecks.MiniUI/SimpleHealthPageEndpointRouteBuilderExtensions.cs b/src/HealthChecks.MiniUI/SimpleHealthPageEndpointRouteBuilderExtensions.cs index 8b6dd4d..ca23272 100644 --- a/src/HealthChecks.MiniUI/SimpleHealthPageEndpointRouteBuilderExtensions.cs +++ b/src/HealthChecks.MiniUI/SimpleHealthPageEndpointRouteBuilderExtensions.cs @@ -34,18 +34,38 @@ public static IEndpointConventionBuilder MapSimpleHealthPage( var healthCheckService = context.RequestServices.GetRequiredService(); 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)) @@ -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); diff --git a/src/HealthChecks.MiniUI/SimpleHealthPageOptions.cs b/src/HealthChecks.MiniUI/SimpleHealthPageOptions.cs index a6dad55..0a0da21 100644 --- a/src/HealthChecks.MiniUI/SimpleHealthPageOptions.cs +++ b/src/HealthChecks.MiniUI/SimpleHealthPageOptions.cs @@ -23,6 +23,12 @@ public sealed class SimpleHealthPageOptions /// public string? AuthorizationPolicy { get; set; } + /// + /// Gets or sets a value indicating whether requests that do not accept text/html + /// (for example curl) receive a text/plain rendering instead of the HTML page. + /// + public bool EnablePlainText { get; set; } + /// /// Gets the HTTP status code mapping used for the page response based on overall health status. /// diff --git a/src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs b/src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs new file mode 100644 index 0000000..148d6bd --- /dev/null +++ b/src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs @@ -0,0 +1,76 @@ +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", "DURATION"]; + + 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(), 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 cells, IReadOnlyList 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"; +} diff --git a/tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs b/tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs new file mode 100644 index 0000000..40f5188 --- /dev/null +++ b/tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs @@ -0,0 +1,172 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; + +namespace HealthChecks.MiniUI.Tests; + +public sealed class PlainTextTests +{ + [Fact] + public void EnablePlainText_DefaultsToFalse() + { + Assert.False(new SimpleHealthPageOptions().EnablePlainText); + } + + [Fact] + public async Task Disabled_AlwaysReturnsHtml() + { + using var host = await CreateHostAsync(configure: null); + + var response = await SendAsync(host, accept: "*/*"); + + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + } + + [Fact] + public async Task Enabled_ReturnsTextWhenHtmlIsNotAccepted() + { + using var host = await CreateHostAsync(o => o.EnablePlainText = true); + + var response = await SendAsync(host, accept: "*/*"); + var body = await response.Content.ReadAsStringAsync(); + + Assert.Equal("text/plain; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Contains("Status: Unhealthy", body, StringComparison.Ordinal); + Assert.Contains("| NAME", body, StringComparison.Ordinal); + Assert.Contains("live-check", body, StringComparison.Ordinal); + Assert.Contains("ready-check", body, StringComparison.Ordinal); + Assert.DoesNotContain(" o.EnablePlainText = true); + + var response = await SendAsync(host, accept: null); + + Assert.Equal("text/plain; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + } + + [Theory] + [InlineData("text/html")] + [InlineData("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")] + public async Task Enabled_ReturnsHtmlWhenHtmlIsAccepted(string accept) + { + using var host = await CreateHostAsync(o => o.EnablePlainText = true); + + var response = await SendAsync(host, accept); + + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + } + + [Fact] + public async Task Enabled_SetsVaryAcceptHeader() + { + using var host = await CreateHostAsync(o => o.EnablePlainText = true); + + var response = await SendAsync(host, accept: "*/*"); + + Assert.Equal("Accept", Assert.Single(response.Headers.Vary)); + } + + [Fact] + public async Task PlainText_UsesConfiguredStatusCode() + { + using var host = await CreateHostAsync(o => + { + o.EnablePlainText = true; + o.StatusCodes.Unhealthy = StatusCodes.Status503ServiceUnavailable; + }); + + var response = await SendAsync(host, accept: "*/*"); + + Assert.Equal(System.Net.HttpStatusCode.ServiceUnavailable, response.StatusCode); + } + + [Fact] + public void TextRenderer_UsesInvariantNumberFormatAndAlignsColumns() + { + var report = new HealthReport( + new Dictionary + { + ["db"] = new HealthReportEntry(HealthStatus.Healthy, "ok", TimeSpan.FromMilliseconds(1.5), null, null), + ["failing"] = new HealthReportEntry(HealthStatus.Unhealthy, "bad", TimeSpan.FromMilliseconds(1002.67), null, null) + }, + TimeSpan.FromMilliseconds(1002.67)); + + var text = new SimpleHealthPageTextRenderer + { + Title = "My App Health", + Report = report, + GeneratedAtUtc = DateTimeOffset.UnixEpoch + }.Render(); + + var lines = text.Split('\n'); + + Assert.Equal("My App Health", lines[0]); + Assert.Equal("Status: Unhealthy", lines[1]); + Assert.Equal("Duration: 1002.67 ms", lines[2]); + Assert.Equal("Generated: 1970-01-01 00:00:00Z", lines[3]); + + var header = Array.FindIndex(lines, l => l.StartsWith("| NAME", StringComparison.Ordinal)); + Assert.True(header > 0); + Assert.Equal(lines[header].Length, lines[header + 1].Length); + Assert.Equal(lines[header].Length, lines[header + 2].Length); + Assert.Equal(lines[header].Length, lines[header + 3].Length); + Assert.Equal("|---------|-----------|------------|", lines[header + 1]); + Assert.Equal("| db | Healthy | 1.5 ms |", lines[header + 2]); + Assert.Equal("| failing | Unhealthy | 1002.67 ms |", lines[header + 3]); + } + + [Fact] + public void TextRenderer_HandlesEmptyReport() + { + var text = new SimpleHealthPageTextRenderer + { + Report = new HealthReport(new Dictionary(), TimeSpan.Zero), + GeneratedAtUtc = DateTimeOffset.UnixEpoch + }.Render(); + + Assert.Contains("Status: Healthy", text, StringComparison.Ordinal); + Assert.DoesNotContain("NAME", text, StringComparison.Ordinal); + } + + private static async Task SendAsync(IHost host, string? accept) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/health"); + + if (accept is not null) + { + request.Headers.TryAddWithoutValidation("Accept", accept); + } + + return await host.GetTestClient().SendAsync(request); + } + + private static Task CreateHostAsync(Action? configure) + { + return new HostBuilder() + .ConfigureWebHost(webHost => + { + webHost.UseTestServer(); + webHost.ConfigureServices(services => + { + services.AddRouting(); + services.AddHealthChecks() + .AddCheck("ready-check", () => HealthCheckResult.Unhealthy("not ready"), tags: ["ready"]) + .AddCheck("live-check", () => HealthCheckResult.Healthy("alive"), tags: ["live"]); + }); + webHost.Configure(app => + { + app.UseRouting(); + app.UseEndpoints(endpoints => endpoints.MapSimpleHealthPage("/health", configure)); + }); + }) + .StartAsync(); + } +} From 324f1452be46d1ef40b0a30ac7c823c54e9e492b Mon Sep 17 00:00:00 2001 From: gprossliner <6724584+gprossliner@users.noreply.github.com> Date: Sat, 5 Sep 2026 14:15:22 +0200 Subject: [PATCH 2/3] added description to text output --- README.md | 10 +++-- .../SimpleHealthPageTextRenderer.cs | 27 +++++++++++++- .../PlainTextTests.cs | 37 +++++++++++++++++-- 3 files changed, 65 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 2052597..38ec6b1 100644 --- a/README.md +++ b/README.md @@ -88,12 +88,14 @@ Status: Unhealthy Duration: 1002.67 ms Generated: 2026-09-05 09:12:33Z -| NAME | STATUS | DURATION | -|---------|-----------|------------| -| db | Healthy | 1.5 ms | -| failing | Unhealthy | 1002.67 ms | +| NAME | STATUS | DESCRIPTION | DURATION | +|---------|-----------|----------------------|------------| +| db | Healthy | connection ok | 1.5 ms | +| failing | Unhealthy | queue backlog too... | 1002.67 ms | ``` +Descriptions are shortened with `...` so the table stays readable in a terminal. + Combine it with `StatusCodes.Unhealthy` so `curl --fail` works without the Accept header routing shown below. ## Example for dynamic response diff --git a/src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs b/src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs index 148d6bd..536b6a4 100644 --- a/src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs +++ b/src/HealthChecks.MiniUI/SimpleHealthPageTextRenderer.cs @@ -6,7 +6,10 @@ namespace HealthChecks.MiniUI; internal sealed class SimpleHealthPageTextRenderer { - private static readonly string[] Headers = ["NAME", "STATUS", "DURATION"]; + 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"; @@ -32,7 +35,13 @@ public string Render() var rows = report.Entries .OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase) - .Select(x => new[] { x.Key, x.Value.Status.ToString(), FormatDuration(x.Value.Duration) }) + .Select(x => new[] + { + x.Key, + x.Value.Status.ToString(), + FormatDescription(x.Value.Description), + FormatDuration(x.Value.Duration) + }) .ToList(); var widths = Headers @@ -73,4 +82,18 @@ private static void AppendRow(StringBuilder builder, IReadOnlyList cells 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), "..."); + } } diff --git a/tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs b/tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs index 40f5188..0e9e689 100644 --- a/tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs +++ b/tests/HealthChecks.MiniUI.Tests/PlainTextTests.cs @@ -118,9 +118,40 @@ public void TextRenderer_UsesInvariantNumberFormatAndAlignsColumns() Assert.Equal(lines[header].Length, lines[header + 1].Length); Assert.Equal(lines[header].Length, lines[header + 2].Length); Assert.Equal(lines[header].Length, lines[header + 3].Length); - Assert.Equal("|---------|-----------|------------|", lines[header + 1]); - Assert.Equal("| db | Healthy | 1.5 ms |", lines[header + 2]); - Assert.Equal("| failing | Unhealthy | 1002.67 ms |", lines[header + 3]); + Assert.Equal("|---------|-----------|-------------|------------|", lines[header + 1]); + Assert.Equal("| db | Healthy | ok | 1.5 ms |", lines[header + 2]); + Assert.Equal("| failing | Unhealthy | bad | 1002.67 ms |", lines[header + 3]); + } + + [Fact] + public void TextRenderer_TruncatesLongDescriptions() + { + var report = new HealthReport( + new Dictionary + { + ["db"] = new HealthReportEntry( + HealthStatus.Unhealthy, + new string('x', 100), + TimeSpan.Zero, + null, + null), + ["multiline"] = new HealthReportEntry( + HealthStatus.Healthy, + "first line\nsecond line", + TimeSpan.Zero, + null, + null) + }, + TimeSpan.Zero); + + var lines = new SimpleHealthPageTextRenderer { Report = report }.Render().Split('\n'); + + var truncated = Array.Find(lines, l => l.StartsWith("| db ", StringComparison.Ordinal))!; + Assert.Contains(new string('x', 37) + "...", truncated, StringComparison.Ordinal); + Assert.DoesNotContain(new string('x', 41), truncated, StringComparison.Ordinal); + + var multiline = Array.Find(lines, l => l.StartsWith("| multiline ", StringComparison.Ordinal))!; + Assert.Contains("first line second line", multiline, StringComparison.Ordinal); } [Fact] From 3a607e2e25f644d824a3ec15da038c1f10f42a5a Mon Sep 17 00:00:00 2001 From: gprossliner <6724584+gprossliner@users.noreply.github.com> Date: Sat, 5 Sep 2026 14:24:00 +0200 Subject: [PATCH 3/3] removed the dynamic response example, as miniui also provides text output directly now --- README.md | 42 ++---------------------- demo/HealthChecks.MiniUI.Demo/Program.cs | 18 +--------- 2 files changed, 4 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 38ec6b1..8c268e3 100644 --- a/README.md +++ b/README.md @@ -96,42 +96,7 @@ Generated: 2026-09-05 09:12:33Z Descriptions are shortened with `...` so the table stays readable in a terminal. -Combine it with `StatusCodes.Unhealthy` so `curl --fail` works without the Accept header routing shown below. - -## Example for dynamic response - -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`) - -```csharp -// Custom Middleware for Accept header based routing -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(); -}); - -// Required in this setup so endpoint routing sees the rewritten /health path. -app.UseRouting(); - -app.MapHealthChecks("/healthz"); - -app.MapSimpleHealthPage("/health-ui", options => -{ - options.Title = "My App Health"; -}); -``` +Combine it with `StatusCodes.Unhealthy` so `curl --fail` works. ## Demo app @@ -145,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 diff --git a/demo/HealthChecks.MiniUI.Demo/Program.cs b/demo/HealthChecks.MiniUI.Demo/Program.cs index 96c82fe..75efaaf 100644 --- a/demo/HealthChecks.MiniUI.Demo/Program.cs +++ b/demo/HealthChecks.MiniUI.Demo/Program.cs @@ -51,23 +51,7 @@ 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");