From 73c7f5b9bfb42ff84c124456bcda2861aacc9842 Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sun, 22 Nov 2026 14:25:37 +0100 Subject: [PATCH 1/4] feat: add optional IHttpClientHintsFeature middleware app.UseHttpClientHintsFeature() registers IHttpClientHintsFeature in HttpContext.Features for every request. The feature exposes View and Snapshot, which return the same values as GetClientHintsView() and GetClientHints(). The middleware does not need AddHttpClientHints() or UseHttpClientHints(), and applications that do not call it are not affected. Closes #2 --- .../Program.cs | 3 + .../Views/Home/Index.cshtml | 5 +- .../HttpClientHintsFeature.cs | 21 ++ .../HttpClientHintsFeatureMiddleware.cs | 20 ++ .../HttpClientHintsRegistration.cs | 17 ++ .../IHttpClientHintsFeature.cs | 35 ++++ src/HttpClientHints.AspNetCore/readme.md | 2 + .../HttpClientHintsFeatureTests.cs | 190 ++++++++++++++++++ version.json | 2 +- 9 files changed, 293 insertions(+), 2 deletions(-) create mode 100644 src/HttpClientHints.AspNetCore/HttpClientHintsFeature.cs create mode 100644 src/HttpClientHints.AspNetCore/HttpClientHintsFeatureMiddleware.cs create mode 100644 src/HttpClientHints.AspNetCore/IHttpClientHintsFeature.cs create mode 100644 tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsFeatureTests.cs diff --git a/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs b/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs index 8a4bb82..8db46f3 100644 --- a/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs +++ b/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs @@ -34,6 +34,9 @@ // Register Http Client Hints Middleware app.UseHttpClientHints(); +// Optional: provide IHttpClientHintsFeature in HttpContext.Features +app.UseHttpClientHintsFeature(); + app.UseRouting(); app.UseAuthorization(); diff --git a/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml b/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml index ba3653d..265730a 100644 --- a/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml +++ b/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml @@ -1,10 +1,13 @@ +@using Microsoft.AspNetCore.Http.Features @using Microsoft.Extensions.Primitives @using MyCSharp.HttpClientHints @using MyCSharp.HttpClientHints.AspNetCore @{ ViewData["Title"] = "Home Page"; - HttpClientHints clientHints = Context.GetClientHints(); + // Registered by app.UseHttpClientHintsFeature() in Program.cs. + // Context.GetClientHints() returns the same snapshot without the feature. + HttpClientHints clientHints = Context.Features.GetRequiredFeature().Snapshot; clientHints.Headers.TryGetValue("Sec-CH-UA-Bitness", out StringValues bitness); } diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsFeature.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsFeature.cs new file mode 100644 index 0000000..47cb01c --- /dev/null +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsFeature.cs @@ -0,0 +1,21 @@ +// Copyright © https://myCSharp.de - all rights reserved + +using Microsoft.AspNetCore.Http; + +namespace MyCSharp.HttpClientHints.AspNetCore; + +/// +/// Default registered by . +/// +/// +/// The middleware creates one instance per request, so the type holds only the context reference and has the minimum +/// object size. and use the extension methods and compute nothing up front. +/// +internal sealed class HttpClientHintsFeature(HttpContext context) : IHttpClientHintsFeature +{ + /// + public HttpClientHintsView View => context.GetClientHintsView(); + + /// + public HttpClientHints Snapshot => context.GetClientHints(); +} diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsFeatureMiddleware.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsFeatureMiddleware.cs new file mode 100644 index 0000000..de6b97e --- /dev/null +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsFeatureMiddleware.cs @@ -0,0 +1,20 @@ +// Copyright © https://myCSharp.de - all rights reserved + +using Microsoft.AspNetCore.Http; + +namespace MyCSharp.HttpClientHints.AspNetCore; + +/// +/// Registers for every request. +/// Added by . +/// +internal sealed class HttpClientHintsFeatureMiddleware(RequestDelegate next) +{ + public Task InvokeAsync(HttpContext context) + { + context.Features.Set(new HttpClientHintsFeature(context)); + + // Nothing runs after the next middleware, so its task is returned without an async state machine. + return next(context); + } +} diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsRegistration.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsRegistration.cs index c700b9d..61108b2 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsRegistration.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsRegistration.cs @@ -84,4 +84,21 @@ public static IApplicationBuilder UseHttpClientHints(this IApplicationBuilder ap return app; } + + /// + /// Adds a middleware that registers in HttpContext.Features for every request. + /// + /// The application builder. + /// The application builder with the middleware added. + /// + /// Middleware and handlers added after this call can read the feature. The middleware does not require + /// or . It creates the feature for every request, + /// even if no handler reads it, and replaces an registered earlier in the pipeline. + /// + public static IApplicationBuilder UseHttpClientHintsFeature(this IApplicationBuilder app) + { + app.Use(static next => new HttpClientHintsFeatureMiddleware(next).InvokeAsync); + + return app; + } } diff --git a/src/HttpClientHints.AspNetCore/IHttpClientHintsFeature.cs b/src/HttpClientHints.AspNetCore/IHttpClientHintsFeature.cs new file mode 100644 index 0000000..1d3772a --- /dev/null +++ b/src/HttpClientHints.AspNetCore/IHttpClientHintsFeature.cs @@ -0,0 +1,35 @@ +// Copyright © https://myCSharp.de - all rights reserved + +using Microsoft.AspNetCore.Http; + +namespace MyCSharp.HttpClientHints.AspNetCore; + +/// +/// Provides the HTTP Client Hints of the current request through . +/// +/// +/// adds a middleware that registers this feature +/// for every request. The registration replaces an that was registered earlier +/// in the pipeline. To use your own implementation, register it after the middleware. Without registration, +/// HttpContext.Features.Get<IHttpClientHintsFeature>() returns . +/// The extension methods in work with and without the feature. +/// The default implementation references the , so do not keep it beyond the request. +/// +public interface IHttpClientHintsFeature +{ + /// + /// Gets a view over the current request headers. Same as . + /// + /// A view that reads the current request headers on every property access. + HttpClientHintsView View { get; } + + /// + /// Gets the snapshot of the Client Hints of the request. Same as . + /// + /// The record that is built on the first access and returned for every further access during the request. + /// + /// The properties keep the values read on the first access. references the + /// request headers themselves, so it shows later changes to the headers. + /// + HttpClientHints Snapshot { get; } +} diff --git a/src/HttpClientHints.AspNetCore/readme.md b/src/HttpClientHints.AspNetCore/readme.md index c484a2f..2d0764c 100644 --- a/src/HttpClientHints.AspNetCore/readme.md +++ b/src/HttpClientHints.AspNetCore/readme.md @@ -4,4 +4,6 @@ Read HTTP Client Hints with .NET Since 3.2, `HttpClientHints` and `HttpClientHintsView` have `DecodedPlatform`, `DecodedPlatformVersion`, `DecodedArchitecture`, and `DecodedModel` properties that return the header values without quotes. [Decoded values](https://github.com/mycsharp/HttpClientHints#decoded-values) +Since 3.3, the optional `app.UseHttpClientHintsFeature()` middleware registers `IHttpClientHintsFeature` in `HttpContext.Features`. [HttpContext feature](https://github.com/mycsharp/HttpClientHints#httpcontext-feature) + https://github.com/mycsharp/HttpClientHints diff --git a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsFeatureTests.cs b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsFeatureTests.cs new file mode 100644 index 0000000..8ea4494 --- /dev/null +++ b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsFeatureTests.cs @@ -0,0 +1,190 @@ +// Copyright © https://myCSharp.de - all rights reserved + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace MyCSharp.HttpClientHints.AspNetCore.UnitTests; + +public class HttpClientHintsFeatureTests +{ + private static readonly IServiceProvider s_emptyServices = new ServiceCollection().BuildServiceProvider(); + + [Fact] + public void UseHttpClientHintsFeature_ReturnsApplicationBuilder() + { + ApplicationBuilder appBuilder = new(s_emptyServices); + + IApplicationBuilder result = appBuilder.UseHttpClientHintsFeature(); + + Assert.Same(appBuilder, result); + } + + [Fact] + public async Task UseHttpClientHintsFeature_WithoutAddHttpClientHints_ProvidesFeatureToHandlers() + { + DefaultHttpContext context = new(); + context.Request.Headers["Sec-CH-UA-Mobile"] = "?1"; + IHttpClientHintsFeature? featureInHandler = null; + RequestDelegate pipeline = BuildFeaturePipeline(ctx => + { + featureInHandler = ctx.Features.Get(); + return Task.CompletedTask; + }); + + await pipeline(context); + + Assert.NotNull(featureInHandler); + Assert.True(featureInHandler.View.Mobile); + Assert.False(context.Response.Headers.ContainsKey("Accept-CH")); + } + + [Fact] + public async Task UseHttpClientHintsFeature_WithUseHttpClientHints_ProvidesFeatureAndAcceptCH() + { + ServiceCollection services = new(); + services.AddHttpClientHints(); + await using ServiceProvider serviceProvider = services.BuildServiceProvider(); + ApplicationBuilder appBuilder = new(serviceProvider); + bool? mobile = null; + + appBuilder.UseHttpClientHints(); + appBuilder.UseHttpClientHintsFeature(); + appBuilder.Run(ctx => + { + mobile = ctx.Features.Get()?.View.Mobile; + return Task.CompletedTask; + }); + DefaultHttpContext context = new(); + context.Request.Headers["Sec-CH-UA-Mobile"] = "?0"; + await appBuilder.Build()(context); + + Assert.False(mobile); + Assert.Contains("Sec-CH-UA-Mobile", context.Response.Headers["Accept-CH"].ToString(), StringComparison.Ordinal); + } + + [Fact] + public async Task UseHttpClientHints_WithoutUseHttpClientHintsFeature_DoesNotRegisterFeature() + { + ServiceCollection services = new(); + services.AddHttpClientHints(); + await using ServiceProvider serviceProvider = services.BuildServiceProvider(); + ApplicationBuilder appBuilder = new(serviceProvider); + + appBuilder.UseHttpClientHints(); + appBuilder.Run(static _ => Task.CompletedTask); + DefaultHttpContext context = new(); + await appBuilder.Build()(context); + + Assert.Null(context.Features.Get()); + Assert.True(context.Response.Headers.ContainsKey("Accept-CH")); + } + + [Fact] + public void UseHttpClientHintsFeature_ReturnsTaskOfNextMiddleware() + { + Task nextTask = new TaskCompletionSource().Task; + RequestDelegate pipeline = BuildFeaturePipeline(_ => nextTask); + + Task result = pipeline(new DefaultHttpContext()); + + Assert.Same(nextTask, result); + } + + [Fact] + public async Task UseHttpClientHintsFeature_ReplacesFeatureRegisteredBefore() + { + DefaultHttpContext context = new(); + IHttpClientHintsFeature existing = new StubFeature(); + context.Features.Set(existing); + + IHttpClientHintsFeature feature = await RegisterFeatureAsync(context); + + Assert.NotSame(existing, feature); + } + + [Fact] + public async Task Feature_View_ReadsCurrentRequestHeaders() + { + DefaultHttpContext context = new(); + context.Request.Headers["Sec-CH-UA-Platform"] = "\"Windows\""; + IHttpClientHintsFeature feature = await RegisterFeatureAsync(context); + + Assert.Equal("Windows", feature.View.DecodedPlatform); + + context.Request.Headers["Sec-CH-UA-Platform"] = "\"Linux\""; + + Assert.Same(context.Request.Headers, feature.View.Headers); + Assert.Equal("\"Linux\"", feature.View.Platform); + Assert.Equal("Linux", feature.View.DecodedPlatform); + } + + [Fact] + public async Task Feature_Snapshot_IsSharedWithGetClientHints() + { + DefaultHttpContext context = new(); + context.Request.Headers["Sec-CH-UA-Model"] = "\"Pixel 9\""; + IHttpClientHintsFeature feature = await RegisterFeatureAsync(context); + + HttpClientHints snapshot = feature.Snapshot; + context.Request.Headers["Sec-CH-UA-Model"] = "\"Pixel 10\""; + + Assert.Same(snapshot, feature.Snapshot); + Assert.Same(snapshot, context.GetClientHints()); + Assert.Equal("Pixel 9", snapshot.DecodedModel); + Assert.Equal("\"Pixel 10\"", feature.View.Model); + } + + [Fact] + public async Task Feature_Snapshot_KeepsValuesButHeadersReferenceRequestHeaders() + { + DefaultHttpContext context = new(); + context.Request.Headers["Sec-CH-UA-Platform"] = "\"Windows\""; + IHttpClientHintsFeature feature = await RegisterFeatureAsync(context); + + HttpClientHints snapshot = feature.Snapshot; + context.Request.Headers["Sec-CH-UA-Platform"] = "\"Linux\""; + + Assert.Equal("\"Windows\"", snapshot.Platform); + Assert.Same(context.Request.Headers, snapshot.Headers); + Assert.Equal("\"Linux\"", snapshot.Headers["Sec-CH-UA-Platform"].ToString()); + } + + [Fact] + public async Task Feature_Snapshot_ReturnsSnapshotCreatedBeforeRegistration() + { + DefaultHttpContext context = new(); + context.Request.Headers["Sec-CH-UA"] = "before"; + HttpClientHints snapshot = context.GetClientHints(); + + IHttpClientHintsFeature feature = await RegisterFeatureAsync(context); + + Assert.Same(snapshot, feature.Snapshot); + } + + private static RequestDelegate BuildFeaturePipeline(RequestDelegate handler) + { + ApplicationBuilder appBuilder = new(s_emptyServices); + appBuilder.UseHttpClientHintsFeature(); + appBuilder.Run(handler); + return appBuilder.Build(); + } + + private static async Task RegisterFeatureAsync(HttpContext context) + { + RequestDelegate pipeline = BuildFeaturePipeline(static _ => Task.CompletedTask); + await pipeline(context).ConfigureAwait(false); + + IHttpClientHintsFeature? feature = context.Features.Get(); + Assert.NotNull(feature); + return feature; + } + + private sealed class StubFeature : IHttpClientHintsFeature + { + public HttpClientHintsView View => default; + + public HttpClientHints Snapshot => throw new NotSupportedException(); + } +} diff --git a/version.json b/version.json index 7832713..ab9b464 100644 --- a/version.json +++ b/version.json @@ -1,6 +1,6 @@ { "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", - "version": "3.2", + "version": "3.3", "nugetPackageVersion": { "semVer": 1 // optional. Set to either 1 or 2 to control how the NuGet package version string is generated. Default is 1. }, From b8aa25bdd2c2060847c49a332a7857f4596c7863 Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sun, 22 Nov 2026 14:25:38 +0100 Subject: [PATCH 2/4] perf: read the response headers once in the Accept-CH middleware The middleware stays async, so a synchronous exception of the next middleware still results in a faulted task and AsyncLocal changes of the next middleware do not flow back to the caller. New tests cover both and the use of configuration values changed after construction. The file is now UTF-8 instead of ISO-8859-1. Adds middleware benchmarks. --- .../HttpClientHintsMiddlewareBenchmarks.cs | 64 +++++++++++++++++++ .../HttpClientHintsRequestMiddleware.cs | 7 +- .../HttpClientHintsRequestMiddlewareTests.cs | 51 +++++++++++++++ 3 files changed, 119 insertions(+), 3 deletions(-) create mode 100644 perf/HttpClientHints.Benchmarks/HttpClientHintsMiddlewareBenchmarks.cs diff --git a/perf/HttpClientHints.Benchmarks/HttpClientHintsMiddlewareBenchmarks.cs b/perf/HttpClientHints.Benchmarks/HttpClientHintsMiddlewareBenchmarks.cs new file mode 100644 index 0000000..1a2515b --- /dev/null +++ b/perf/HttpClientHints.Benchmarks/HttpClientHintsMiddlewareBenchmarks.cs @@ -0,0 +1,64 @@ +// Copyright © https://myCSharp.de - all rights reserved + +using BenchmarkDotNet.Attributes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using MyCSharp.HttpClientHints.AspNetCore; + +namespace HttpClientHints.Benchmarks; + +[MemoryDiagnoser] +public class HttpClientHintsMiddlewareBenchmarks +{ + private ServiceProvider _serviceProvider = null!; + private RequestDelegate _acceptChPipeline = null!; + private RequestDelegate _featurePipeline = null!; + private RequestDelegate _bothPipeline = null!; + private DefaultHttpContext _context = null!; + + [GlobalSetup] + public void Setup() + { + ServiceCollection services = new(); + services.AddHttpClientHints(options => options.Lifetime = TimeSpan.FromDays(31)); + _serviceProvider = services.BuildServiceProvider(); + + _acceptChPipeline = BuildPipeline(static app => app.UseHttpClientHints()); + _featurePipeline = BuildPipeline(static app => app.UseHttpClientHintsFeature()); + _bothPipeline = BuildPipeline(static app => app.UseHttpClientHints().UseHttpClientHintsFeature()); + + // Every invocation reuses this context. Servers such as Kestrel allocate differently when a feature is registered. + _context = new DefaultHttpContext(); + _context.Request.Headers["Sec-CH-UA"] = "\"Chromium\";v=\"131\", \"Not;A=Brand\";v=\"99\", \"Google Chrome\";v=\"131\""; + _context.Request.Headers["Sec-CH-UA-Platform"] = "\"Windows\""; + _context.Request.Headers["Sec-CH-UA-Mobile"] = "?0"; + } + + [GlobalCleanup] + public void Cleanup() => _serviceProvider.Dispose(); + + [Benchmark] + public Task UseHttpClientHints() => _acceptChPipeline(_context); + + [Benchmark] + public Task UseHttpClientHintsFeature() => _featurePipeline(_context); + + [Benchmark] + public Task UseHttpClientHintsAndFeature() => _bothPipeline(_context); + + [Benchmark] + public bool? UseHttpClientHintsFeatureAndReadView() + { + _ = _featurePipeline(_context); + return _context.Features.Get()!.View.Mobile; + } + + private RequestDelegate BuildPipeline(Action configure) + { + ApplicationBuilder app = new(_serviceProvider); + configure(app); + app.Run(static _ => Task.CompletedTask); + return app.Build(); + } +} diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsRequestMiddleware.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsRequestMiddleware.cs index e5d5db5..e13145e 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsRequestMiddleware.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsRequestMiddleware.cs @@ -1,4 +1,4 @@ -// Copyright © https://myCSharp.de - all rights reserved +// Copyright © https://myCSharp.de - all rights reserved using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; @@ -28,11 +28,12 @@ public async Task InvokeAsync(HttpContext context) if (_options.HasResponseHeaders) { // Set headers directly without additional checks - context.Response.Headers["Accept-CH"] = _options.ResponseHeader; + IHeaderDictionary headers = context.Response.Headers; + headers["Accept-CH"] = _options.ResponseHeader; if (_options.HasLifetime) { - context.Response.Headers["Accept-CH-Lifetime"] = _options.LifeTime; + headers["Accept-CH-Lifetime"] = _options.LifeTime; } } diff --git a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRequestMiddlewareTests.cs b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRequestMiddlewareTests.cs index 34fe794..cc97088 100644 --- a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRequestMiddlewareTests.cs +++ b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsRequestMiddlewareTests.cs @@ -88,4 +88,55 @@ public async Task InvokeAsync_WithoutLifetime_DoesNotAddAcceptCHLifetimeHeader() Assert.Equal("User-Agent", context.Response.Headers["Accept-CH"]); Assert.False(context.Response.Headers.ContainsKey("Accept-CH-Lifetime")); } + + [Fact] + public async Task InvokeAsync_WhenNextThrowsSynchronously_ReturnsFaultedTask() + { + InvalidOperationException exception = new("next failed"); + IOptions options = Options.Create(new HttpClientHintsMiddlewareConfig + { + ResponseHeader = "User-Agent" + }); + HttpClientHintsRequestMiddleware middleware = new(_ => throw exception, options); + + Task task = middleware.InvokeAsync(new DefaultHttpContext()); + + Assert.True(task.IsFaulted); + Assert.Same(exception, await Assert.ThrowsAsync(() => task)); + } + + [Fact] + public async Task InvokeAsync_DoesNotFlowAsyncLocalChangesOfNextMiddlewareToCaller() + { + AsyncLocal value = new(); + IOptions options = Options.Create(new HttpClientHintsMiddlewareConfig + { + ResponseHeader = "User-Agent" + }); + HttpClientHintsRequestMiddleware middleware = new(_ => + { + value.Value = "set by next"; + return Task.CompletedTask; + }, options); + + Task task = middleware.InvokeAsync(new DefaultHttpContext()); + + Assert.Null(value.Value); + await task; + } + + [Fact] + public async Task InvokeAsync_UsesConfigurationChangedAfterConstruction() + { + HttpClientHintsMiddlewareConfig config = new() { ResponseHeader = string.Empty }; + HttpClientHintsRequestMiddleware middleware = new(static _ => Task.CompletedTask, Options.Create(config)); + config.ResponseHeader = "Sec-CH-UA-Mobile"; + config.LifeTime = "60"; + DefaultHttpContext context = new(); + + await middleware.InvokeAsync(context); + + Assert.Equal("Sec-CH-UA-Mobile", context.Response.Headers["Accept-CH"]); + Assert.Equal("60", context.Response.Headers["Accept-CH-Lifetime"]); + } } From b9b74b348c14b54d123f37deeb5ad4778cac3281 Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sun, 22 Nov 2026 14:25:38 +0100 Subject: [PATCH 3/4] ci: require 100% coverage for each package Assert-CodeCoverage.ps1 now fails if MyCSharp.HttpClientHints or MyCSharp.HttpClientHints.AspNetCore is missing from the report or below the threshold. The threshold is 100% in CI, the Justfile, and the script. --- .github/workflows/build-and-test.yml | 2 +- Justfile | 2 +- eng/Assert-CodeCoverage.ps1 | 37 ++++++++++++++++++++++++---- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index c2c1a80..d137b9f 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -72,7 +72,7 @@ jobs: - name: Check code coverage shell: pwsh - run: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults -Threshold 90 + run: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults -Threshold 100 - name: Upload test results if: always() && inputs.upload-test-results diff --git a/Justfile b/Justfile index f867caf..6e6b246 100644 --- a/Justfile +++ b/Justfile @@ -8,7 +8,7 @@ CONFIG := "Debug" TFM := "net11.0" BENCH_PRJ := "perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj" COV_DIR := "TestResults/coverage" -COV_MIN := "90" +COV_MIN := "100" # ===== Default / Help ===== default: help diff --git a/eng/Assert-CodeCoverage.ps1 b/eng/Assert-CodeCoverage.ps1 index 6aff5fb..077e262 100644 --- a/eng/Assert-CodeCoverage.ps1 +++ b/eng/Assert-CodeCoverage.ps1 @@ -1,5 +1,6 @@ -# Fails when the merged Cobertura report in the results directory is below the coverage threshold. -# Usage: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory ./TestResults -Threshold 90 +# Fails when the merged Cobertura report in the results directory is below the coverage threshold +# or does not contain every required package. +# Usage: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory ./TestResults -Threshold 100 [CmdletBinding()] param( @@ -7,7 +8,10 @@ param( [string] $ResultsDirectory, [ValidateRange(0, 100)] - [double] $Threshold = 90 + [double] $Threshold = 100, + + [ValidateNotNullOrEmpty()] + [string[]] $RequiredPackages = @('MyCSharp.HttpClientHints', 'MyCSharp.HttpClientHints.AspNetCore') ) $ErrorActionPreference = 'Stop' @@ -30,7 +34,30 @@ Write-Host ([string]::Format($invariant, 'Coverage report: {0}', $report.FullNam Write-Host ([string]::Format($invariant, 'Line coverage: {0:F2} % (minimum {1} %)', $lineRate, $Threshold)) Write-Host ([string]::Format($invariant, 'Branch coverage: {0:F2} % (minimum {1} %)', $branchRate, $Threshold)) -if ($lineRate -lt $Threshold -or $branchRate -lt $Threshold) { - Write-Error ([string]::Format($invariant, 'Code coverage is below the minimum of {0} %.', $Threshold)) +$failed = $lineRate -lt $Threshold -or $branchRate -lt $Threshold + +# A report without one of the packages would otherwise pass with the coverage of the remaining packages. +$packages = @($coverage.coverage.packages.package) +foreach ($name in $RequiredPackages) { + $found = @($packages | Where-Object { $_.name -eq $name }) + if ($found.Count -eq 0) { + Write-Host "Package $name`: missing from the coverage report" + $failed = $true + continue + } + + foreach ($package in $found) { + $packageLineRate = [double]::Parse($package.'line-rate', $invariant) * 100 + $packageBranchRate = [double]::Parse($package.'branch-rate', $invariant) * 100 + Write-Host ([string]::Format($invariant, 'Package {0}: line {1:F2} %, branch {2:F2} %', $name, $packageLineRate, $packageBranchRate)) + + if ($packageLineRate -lt $Threshold -or $packageBranchRate -lt $Threshold) { + $failed = $true + } + } +} + +if ($failed) { + Write-Error ([string]::Format($invariant, 'Code coverage is below the minimum of {0} % or a required package is missing.', $Threshold)) exit 1 } From d3c98dcb56b318771c74f314fb9366c1d3d3a162 Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sun, 22 Nov 2026 14:25:38 +0100 Subject: [PATCH 4/4] docs: document the HttpContext feature and update the benchmarks --- README.md | 68 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 56 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index adfb13f..86e3670 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ app.UseRouting(); ... ``` -The client hints are not read by a separate dependency injection registration, but as an extension method to the header collection or to the HttpContext object. +The client hints are not read by a separate dependency injection registration, but as an extension method to the header collection or to the HttpContext object. Optionally, a separate middleware also provides them as an `HttpContext` feature, see [HttpContext feature](#httpcontext-feature). ```csharp using MyCSharp.HttpClientHints.AspNetCore; @@ -72,6 +72,35 @@ bool? isMobile = view.Mobile; Since potentially all client hints are optional, all properties are potentially nullable, which means that the client has not provided this data. +## HttpContext feature + +Since 3.3, you can register `IHttpClientHintsFeature` in `HttpContext.Features` with a separate middleware. Add it only if you want to read the Client Hints through the feature: + +```csharp +app.UseHttpClientHints(); + +// Optional: provide IHttpClientHintsFeature in HttpContext.Features +app.UseHttpClientHintsFeature(); +``` + +`UseHttpClientHintsFeature()` does not require `AddHttpClientHints()` or `UseHttpClientHints()`. Every middleware and handler after it can read the Client Hints from the feature: + +```csharp +IHttpClientHintsFeature? feature = httpContext.Features.Get(); +bool? isMobile = feature?.View.Mobile; +``` + +| Property | Same as | +| --- | --- | +| `View` | `httpContext.GetClientHintsView()` | +| `Snapshot` | `httpContext.GetClientHints()`, including the cached instance | + +`Snapshot` keeps the values read on the first access. `Snapshot.Headers` references the request headers, so it shows later changes to them. + +The middleware registers the feature for every request, whether or not `Accept-CH` is configured, because browsers send some Client Hints such as `Sec-CH-UA-Mobile` without a request. The registration replaces an `IHttpClientHintsFeature` registered earlier in the pipeline. Register your own implementation after `app.UseHttpClientHintsFeature()`. The feature references the `HttpContext`, so do not keep it beyond the request. + +Without `UseHttpClientHintsFeature()`, requests have no additional cost, and `Features.Get()` returns `null`. The extension methods work in both cases. With it, the feature is created for every request, even if no handler reads it. In the [benchmark](#benchmark), which reuses one `DefaultHttpContext`, the feature middleware takes about 12 ns and allocates 24 B per request. Together with `UseHttpClientHints()`, the pipeline takes about 19 ns more than `UseHttpClientHints()` alone, because `HttpContext` looks up its cached features again after the registration. The cost depends on the server: in a test with Kestrel on .NET 11, the registration allocated 24 B or 112 B per request, depending on whether Kestrel reused its request object. + ## Decoded values Browsers send `Sec-CH-UA-Platform`, `Sec-CH-UA-Platform-Version`, `Sec-CH-UA-Arch`, and `Sec-CH-UA-Model` as quoted strings, for example `Sec-CH-UA-Platform: "Windows"`. `Platform`, `PlatformVersion`, `Architecture`, and `Model` return these header values as sent, including the quotes. Since 3.2, the matching `Decoded*` properties return the value without quotes and escapes. @@ -145,7 +174,7 @@ dotnet build -c Release dotnet test -c Release --no-build ``` -Line and branch coverage must stay at or above 90 %. CI collects coverage on every build and fails below this threshold. Run the same check locally with `just test-cov`, or call `./eng/Assert-CodeCoverage.ps1` after a test run with `--coverage --coverage-output-format cobertura`. +Line and branch coverage of both packages must stay at 100 %. CI collects coverage on every build and fails below this threshold. Run the same check locally with `just test-cov`, or call `./eng/Assert-CodeCoverage.ps1` after a test run with `--coverage --coverage-output-format cobertura`. ## Release @@ -161,12 +190,12 @@ The workflow requires a Trusted Publishing policy on NuGet.org for the `MyCSharp ## Benchmark -Reading header values from the view does not allocate, and a snapshot allocates only the record. A `Decoded*` property allocates the decoded string of a quoted value on every access. Run the benchmarks with `dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6`. +Run the benchmarks with `dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6`. Both tables below come from one run of this command. ``` BenchmarkDotNet v0.16.0-preview.2, Windows 10 (10.0.19045.7846/22H2/2022Update) AMD Ryzen 9 9950X 4.30GHz, 1 CPU, 32 logical and 16 physical cores -Memory: 61,64 GB Total, 31,05 GB Available +Memory: 61,64 GB Total, 35,59 GB Available .NET SDK 11.0.100 [Host] : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4 Job-ZRYWOI : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4 @@ -175,14 +204,29 @@ IterationCount=15 IterationTime=200ms LaunchCount=2 WarmupCount=6 ``` -| Method | Mean | Error | StdDev | Gen0 | Allocated | -|-------------------------------------- |----------:|----------:|----------:|-------:|----------:| -| ReadViewProperties | 18.956 ns | 0.3872 ns | 0.5299 ns | - | - | -| ReadDecodedViewProperties | 36.646 ns | 0.5085 ns | 0.6961 ns | 0.0042 | 72 B | -| GetClientHintsFromHeaders | 57.352 ns | 0.4389 ns | 0.6295 ns | 0.0052 | 88 B | -| GetClientHintsFromHeadersWithoutHints | 49.915 ns | 0.7589 ns | 1.1124 ns | 0.0050 | 88 B | -| GetClientHintsFromContextUncached | 71.118 ns | 0.5539 ns | 0.8119 ns | 0.0049 | 88 B | -| GetClientHintsFromContextCached | 6.052 ns | 0.1073 ns | 0.1538 ns | - | - | +### Reading Client Hints + +Reading header values from the view does not allocate, and a snapshot allocates only the record. A `Decoded*` property allocates the decoded string of a quoted value on every access. + +| Method | Mean | Error | StdDev | Median | Gen0 | Allocated | +|-------------------------------------- |----------:|----------:|----------:|----------:|-------:|----------:| +| ReadViewProperties | 18.471 ns | 0.2174 ns | 0.3118 ns | 18.466 ns | - | - | +| ReadDecodedViewProperties | 36.670 ns | 0.7575 ns | 1.0113 ns | 37.392 ns | 0.0043 | 72 B | +| GetClientHintsFromHeaders | 56.993 ns | 0.5361 ns | 0.7688 ns | 56.722 ns | 0.0051 | 88 B | +| GetClientHintsFromHeadersWithoutHints | 48.849 ns | 0.4774 ns | 0.7146 ns | 48.529 ns | 0.0052 | 88 B | +| GetClientHintsFromContextUncached | 71.006 ns | 0.8836 ns | 1.2386 ns | 70.255 ns | 0.0049 | 88 B | +| GetClientHintsFromContextCached | 6.196 ns | 0.2700 ns | 0.4041 ns | 6.188 ns | - | - | + +### Middleware + +The middleware benchmarks run pipelines built with `ApplicationBuilder`. They reuse one `DefaultHttpContext`, and the last handler completes synchronously. `UseHttpClientHints()` sets `Accept-CH` and `Accept-CH-Lifetime` and does not allocate in this setup. If a later middleware completes asynchronously, it allocates its async state machine, as in earlier versions. `UseHttpClientHintsFeature()` allocates the 24-byte feature and returns the task of the next middleware directly. Registering the feature changes the revision of the feature collection, so `HttpContext` looks up the features it has cached again. Other servers can allocate more for the registration, see [HttpContext feature](#httpcontext-feature). + +| Method | Mean | Error | StdDev | Gen0 | Allocated | +|------------------------------------- |---------:|---------:|---------:|-------:|----------:| +| UseHttpClientHints | 17.60 ns | 0.143 ns | 0.214 ns | - | - | +| UseHttpClientHintsFeature | 12.25 ns | 0.312 ns | 0.458 ns | 0.0014 | 24 B | +| UseHttpClientHintsAndFeature | 36.76 ns | 0.384 ns | 0.526 ns | 0.0013 | 24 B | +| UseHttpClientHintsFeatureAndReadView | 41.71 ns | 0.400 ns | 0.574 ns | 0.0014 | 24 B | ## Samples