Skip to content

feat: add optional IHttpClientHintsFeature middleware, enforce 100% coverage - #22

Merged
BenjaminAbt merged 4 commits into
mainfrom
feat/http-client-hints-feature
Nov 22, 2026
Merged

BenjaminAbt merged 4 commits into
mainfrom
feat/http-client-hints-feature

Conversation

@BenjaminAbt

Copy link
Copy Markdown
Member

Summary

Closes #2.

This PR adds IHttpClientHintsFeature and an optional middleware, app.UseHttpClientHintsFeature(), that registers the feature in HttpContext.Features for every request. Middleware and handlers after it can read the Client Hints with HttpContext.Features.Get<IHttpClientHintsFeature>(). Applications that do not call UseHttpClientHintsFeature() are not affected.

app.UseHttpClientHints();

// Optional: provide IHttpClientHintsFeature in HttpContext.Features
app.UseHttpClientHintsFeature();
IHttpClientHintsFeature? feature = httpContext.Features.Get<IHttpClientHintsFeature>();
bool? isMobile = feature?.View.Mobile;

The PR also raises the coverage requirement from 90% to 100% for each package, and the Accept-CH middleware now reads the response headers once. The version goes from 3.2 to 3.3.

Changes

Library (MyCSharp.HttpClientHints.AspNetCore)

  • IHttpClientHintsFeature (public, new)
    • View is the same as httpContext.GetClientHintsView().
    • Snapshot is the same as httpContext.GetClientHints(), including the instance that is cached for the request.
  • HttpClientHintsFeature (internal sealed, new): the default implementation.
    • It holds only the HttpContext, so it has the minimum object size of 24 B on x64.
    • View and Snapshot call the existing extension methods and compute nothing up front.
  • UseHttpClientHintsFeature() (public, new) and HttpClientHintsFeatureMiddleware (internal sealed, new)
    • The middleware registers the feature for every request, whether or not Accept-CH is configured.
    • It needs neither AddHttpClientHints() nor UseHttpClientHints().
    • It is added with app.Use(...) and needs no reflection.
    • It returns the task of the next middleware directly, without an async state machine.
  • HttpClientHintsRequestMiddleware
    • It reads context.Response.Headers once instead of twice. Its behavior does not change: it stays async and reads the configuration on every request.
    • The file is now UTF-8 instead of ISO-8859-1. The © in the header comment was broken.
  • HttpClientHintsOptions, HttpClientHintsMiddlewareConfig, and AddHttpClientHints() are unchanged.

Tests

  • New HttpClientHintsFeatureTests covers:
    • The feature without AddHttpClientHints(), and together with UseHttpClientHints().
    • UseHttpClientHints() alone does not register the feature.
    • The middleware returns the task of the next middleware.
    • The registration replaces a feature registered earlier in the pipeline.
    • View reads the current headers.
    • Snapshot is the instance that GetClientHints() returns, also when it was created before the registration.
    • Snapshot keeps its values, while Snapshot.Headers shows later header changes.
  • New tests in HttpClientHintsRequestMiddlewareTests pin down existing behavior of the Accept-CH middleware:
    • A synchronous exception of the next middleware results in a faulted task.
    • AsyncLocal changes of the next middleware do not flow back to the caller.
    • Configuration values changed after construction are used.

CI and tooling

  • The coverage threshold is 100% in build-and-test.yml, the Justfile, and the default of eng/Assert-CodeCoverage.ps1.
  • The script has a new parameter, -RequiredPackages, with both packages as default. It fails when a package is missing from the report or below the threshold. Before, a report with only MyCSharp.HttpClientHints passed with 100%.

Benchmarks

  • New HttpClientHintsMiddlewareBenchmarks runs pipelines built with ApplicationBuilder:
    • UseHttpClientHints() alone.
    • UseHttpClientHintsFeature() alone.
    • Both together.
    • The feature with a read of View.Mobile.

Documentation and sample

  • The README has a new "HttpContext feature" section. It covers:
    • The registration.
    • The two properties.
    • Replacement of an earlier feature.
    • Why Snapshot.Headers shows later header changes.
    • The lifetime of the feature.
    • The cost.
  • The benchmark section has a "Reading Client Hints" and a "Middleware" table from one new run.
  • The "Build and test" section states the 100% requirement for both packages.
  • The package readme of MyCSharp.HttpClientHints.AspNetCore mentions the middleware.
  • The MVC sample calls app.UseHttpClientHintsFeature() and reads the snapshot from the feature.

Notes for reviewers

  • Why a separate middleware instead of an option of AddHttpClientHints(): Applications that do not use the feature pay nothing, not even a flag check per request. The Accept-CH middleware keeps its behavior, and the feature also works in applications that do not send Accept-CH.
  • Why the feature is registered regardless of Accept-CH: Browsers send some Client Hints, such as Sec-CH-UA, Sec-CH-UA-Mobile, and Sec-CH-UA-Platform, without being asked.
  • Cost of the registration: The feature middleware alone takes about 12 ns and allocates 24 B. Together with UseHttpClientHints(), the pipeline takes about 19 ns more than UseHttpClientHints() alone. Features.Set changes the revision of the feature collection, so HttpContext looks up the features it has cached again. These numbers come from a reused DefaultHttpContext. In a separate test with Kestrel on .NET 11, the registration allocated 24 B or 112 B per request, depending on whether Kestrel reused its request object. The README states both.
  • The new middleware is not async: It returns the task of the next middleware directly, like many middlewares in ASP.NET Core. If the next middleware throws synchronously, the exception propagates from InvokeAsync instead of as a faulted task. It is a new middleware, so no existing caller depends on the other behavior.
  • The Accept-CH middleware stays async on purpose: Returning the task of the next middleware directly would save 118 B per request when the rest of the pipeline completes asynchronously. Measured with a copy of the middleware: 96 B instead of 214 B. It would also change two observable behaviors: a synchronous exception of the next middleware would propagate from InvokeAsync instead of as a faulted task, and AsyncLocal changes of the next middleware would flow back to the caller. That would need a separate decision, so this PR leaves it out. The new tests fail if one of the two behaviors changes.
  • Feature contract:
    • The registration replaces an IHttpClientHintsFeature registered earlier. Applications that need their own implementation register it after UseHttpClientHintsFeature().
    • The default implementation references the HttpContext, so it must not be kept beyond the request.
    • The XML docs and the README describe both points.

Testing

  • dotnet build -c Release: 0 warnings, 0 errors, with TreatWarningsAsErrors enabled.
  • dotnet test -c Release --no-build --results-directory TestResults --results-directory-layout per-module -- --coverage --coverage-output-format cobertura: 296 tests passed on net8.0, net9.0, net10.0, and net11.0.
  • ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults: 100.00% line and branch coverage for MyCSharp.HttpClientHints and for MyCSharp.HttpClientHints.AspNetCore.
  • The same script on two modified copies of that report exits with code 1:
    • Without the MyCSharp.HttpClientHints.AspNetCore package.
    • With 95% branch coverage for that package, while the overall rate stays at 100%.
  • dotnet format --verify-no-changes: no changes.
  • The MVC sample on net11.0, requested with curl:
    • With Sec-CH-UA-Platform: "Windows" and Sec-CH-UA-Mobile: ?0, it returns HTTP 200 with Accept-CH and Accept-CH-Lifetime. The page shows "Windows" next to Windows and False for mobile, read from IHttpClientHintsFeature.Snapshot.
    • Without Client Hints, it returns HTTP 200.
  • All checks ran on Windows. The Linux run is left to CI.

Benchmark

AMD Ryzen 9 9950X, Windows 10 x64, .NET SDK 11.0.100, .NET 11.0.0, BenchmarkDotNet 0.16.0-preview.2, --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6. Both tables are in the README.

Pipeline Mean Allocated
UseHttpClientHints() 17.60 ns 0 B
UseHttpClientHintsFeature() 12.25 ns 24 B
Both 36.76 ns 24 B
UseHttpClientHintsFeature() and read View.Mobile 41.71 ns 24 B

Accept-CH middleware compared with a copy of the version on main, measured side by side in one session:

Next middleware main This PR
Completes synchronously 18.94 ns, 0 B 16.97 ns, 0 B
Completes asynchronously (Task.Yield) 294 ns, 214 B 307 ns, 209 B

With the asynchronous next middleware, Task.Yield dominates the time and both versions are within the noise.

This PR does not change the code that the "Reading Client Hints" benchmarks run. Their new results differ from the ones on main by at most 1.1 ns or 2.6% per benchmark, which is variation between the two runs.

Reproduce

dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6

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
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.
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.
@BenjaminAbt BenjaminAbt added the enhancement New feature or request label Nov 22, 2026
@BenjaminAbt
BenjaminAbt merged commit 58d4aa6 into main Nov 22, 2026
1 check passed
@BenjaminAbt
BenjaminAbt deleted the feat/http-client-hints-feature branch November 22, 2026 13:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add HTTP Feature?

1 participant