From 501c84028a148586a937c907ee3d38e5bb0a8640 Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sat, 21 Nov 2026 15:45:12 +0100 Subject: [PATCH 1/3] feat!: decode Client Hints structured strings, enforce 90% coverage - Decode the RFC 9651 strings of Sec-CH-UA-Platform, Sec-CH-UA-Platform-Version, Sec-CH-UA-Arch, and Sec-CH-UA-Model in Platform, PlatformVersion, Architecture, and Model - Add RawPlatform, RawPlatformVersion, RawArchitecture, and RawModel to HttpClientHintsView and the HttpClientHints record - Bump the version to 4.0 and add an upgrade guide to the README - Collect code coverage in CI and fail below 90% line or branch coverage - Add a raw-read benchmark and update the README benchmark results --- .github/workflows/build-and-test.yml | 10 +- Justfile | 6 +- README.md | 44 ++++++-- eng/Assert-CodeCoverage.ps1 | 36 ++++++ .../HttpClientHintBenchmarks.cs | 8 ++ .../HttpClientHintsHttpContextExtensions.cs | 5 +- .../HttpClientHintsView.cs | 106 ++++++++++++++++-- src/HttpClientHints.AspNetCore/readme.md | 2 + src/HttpClientHints/HttpClientHints.cs | 29 ++++- src/HttpClientHints/readme.md | 2 + ...tpClientHintsHttpContextExtensionsTests.cs | 104 ++++++++++++++--- version.json | 2 +- 12 files changed, 312 insertions(+), 42 deletions(-) create mode 100644 eng/Assert-CodeCoverage.ps1 diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 46a717c..c2c1a80 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -68,14 +68,20 @@ jobs: run: dotnet build --configuration ${{ inputs.configuration }} --no-restore /p:Version=${{ steps.nbgv.outputs.SemVer2 }} - name: Test - run: dotnet test --configuration ${{ inputs.configuration }} --no-build --results-directory TestResults --results-directory-layout per-module -- --report-trx + run: dotnet test --configuration ${{ inputs.configuration }} --no-build --results-directory TestResults --results-directory-layout per-module -- --report-trx --coverage --coverage-output-format cobertura + + - name: Check code coverage + shell: pwsh + run: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory TestResults -Threshold 90 - name: Upload test results if: always() && inputs.upload-test-results uses: actions/upload-artifact@v6 with: name: test-results - path: '**/TestResults/**/*.trx' + path: | + **/TestResults/**/*.trx + **/TestResults/**/*.cobertura.xml - name: Pack NuGet packages if: inputs.create-pack diff --git a/Justfile b/Justfile index 22184d4..f867caf 100644 --- a/Justfile +++ b/Justfile @@ -7,6 +7,8 @@ set shell := ["pwsh", "-c"] CONFIG := "Debug" TFM := "net11.0" BENCH_PRJ := "perf/HttpClientHints.Benchmarks/HttpClientHints.Benchmarks.csproj" +COV_DIR := "TestResults/coverage" +COV_MIN := "90" # ===== Default / Help ===== default: help @@ -46,7 +48,9 @@ test *ARGS: dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" {{ARGS}} test-cov: - dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" --results-directory-layout per-module -- --coverage --coverage-output-format cobertura + if (Test-Path "{{COV_DIR}}") { Remove-Item "{{COV_DIR}}" -Recurse -Force } + dotnet test --configuration "{{CONFIG}}" --framework "{{TFM}}" --results-directory "{{COV_DIR}}" --results-directory-layout per-module -- --coverage --coverage-output-format cobertura + ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory "{{COV_DIR}}" -Threshold {{COV_MIN}} test-filter QUERY: diff --git a/README.md b/README.md index 8f76df7..4403a80 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,29 @@ HttpClientHints clientHints = HttpClientHintsHttpContextExtensions.GetClientHint Since potentially all client hints are optional, all properties are potentially nullable, which means that the client has not provided this data. +## Upgrading to 4.0 + +**Breaking change.** Version 4.0 changes what four properties return when Client Hints are read through `GetClientHints()` or `GetClientHintsView()`. They now decode the HTTP Structured Field string. To keep using the original value as returned in 3.x, switch to the corresponding `Raw*` property. + +| Decoded property | Raw property | Request header | +| --- | --- | --- | +| `Platform` | `RawPlatform` | `Sec-CH-UA-Platform` | +| `PlatformVersion` | `RawPlatformVersion` | `Sec-CH-UA-Platform-Version` | +| `Architecture` | `RawArchitecture` | `Sec-CH-UA-Arch` | +| `Model` | `RawModel` | `Sec-CH-UA-Model` | + +For a request with `Sec-CH-UA-Platform: "Windows"`, both forms are available. + +```csharp +HttpClientHints hints = httpContext.GetClientHints(); +bool isWindows = hints.Platform == "Windows"; +string? originalPlatformHeader = hints.RawPlatform; // Contains the two quote characters. +``` + +An absent header yields `null` for both properties. A quoted empty value such as `Sec-CH-UA-Model: ""` decodes to `string.Empty`. Unquoted values pass through as supplied. A malformed quoted value yields `null` in the decoded property and remains available in the raw property. Parameters are not supported: `Sec-CH-UA-Platform: "Windows";a=1` also yields `null` in the decoded property. [RFC 9651 § 4.2.5](https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.5) + +`UA` and `FullVersionList` expose serialized brand lists. The `Headers` collection provides access to all original header values. If you construct an `HttpClientHints` record directly, supply the decoded values to its constructor and set the raw properties in an object initializer when you have the original values. A `with` expression that changes a decoded property, such as `hints with { Platform = "Linux" }`, leaves the matching `Raw*` property unchanged. + ## Customization The `Additional` property can be used to define your own headers that are to be requested. @@ -91,12 +114,16 @@ 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`. + ## Benchmark +Reading `Raw*` properties from the view does not allocate. Reading a decoded property allocates the decoded string, and a snapshot stores both forms. Run the benchmarks with `dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6`. + ``` 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,83 GB Available +Memory: 61,64 GB Total, 21,42 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 @@ -105,13 +132,14 @@ IterationCount=15 IterationTime=200ms LaunchCount=2 WarmupCount=6 ``` -| Method | Mean | Error | StdDev | Gen0 | Allocated | -|-------------------------------------- |----------:|----------:|----------:|-------:|----------:| -| ReadViewProperties | 18.688 ns | 0.2959 ns | 0.4337 ns | - | - | -| GetClientHintsFromHeaders | 58.697 ns | 0.7625 ns | 1.1176 ns | 0.0051 | 88 B | -| GetClientHintsFromHeadersWithoutHints | 51.311 ns | 0.8545 ns | 1.2255 ns | 0.0052 | 88 B | -| GetClientHintsFromContextUncached | 76.252 ns | 2.8269 ns | 4.0542 ns | 0.0050 | 88 B | -| GetClientHintsFromContextCached | 6.174 ns | 0.1132 ns | 0.1623 ns | - | - | +| Method | Mean | Error | StdDev | Median | Gen0 | Allocated | +|-------------------------------------- |-----------:|----------:|----------:|-----------:|-------:|----------:| +| ReadViewProperties | 38.403 ns | 1.2810 ns | 1.8777 ns | 37.723 ns | 0.0042 | 72 B | +| ReadRawViewProperties | 19.796 ns | 0.5348 ns | 0.7671 ns | 19.829 ns | - | - | +| GetClientHintsFromHeaders | 96.731 ns | 2.1783 ns | 3.1241 ns | 96.137 ns | 0.0134 | 232 B | +| GetClientHintsFromHeadersWithoutHints | 61.318 ns | 1.8116 ns | 2.6554 ns | 59.624 ns | 0.0072 | 120 B | +| GetClientHintsFromContextUncached | 108.202 ns | 1.5130 ns | 2.0709 ns | 108.719 ns | 0.0136 | 232 B | +| GetClientHintsFromContextCached | 6.524 ns | 0.0837 ns | 0.1227 ns | 6.510 ns | - | - | ## Samples diff --git a/eng/Assert-CodeCoverage.ps1 b/eng/Assert-CodeCoverage.ps1 new file mode 100644 index 0000000..6aff5fb --- /dev/null +++ b/eng/Assert-CodeCoverage.ps1 @@ -0,0 +1,36 @@ +# Fails when the merged Cobertura report in the results directory is below the coverage threshold. +# Usage: ./eng/Assert-CodeCoverage.ps1 -ResultsDirectory ./TestResults -Threshold 90 + +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [string] $ResultsDirectory, + + [ValidateRange(0, 100)] + [double] $Threshold = 90 +) + +$ErrorActionPreference = 'Stop' + +$reports = @(Get-ChildItem -Path $ResultsDirectory -Recurse -Filter '*.cobertura.xml') +$report = $reports | Where-Object Name -like 'merged-*' | Sort-Object LastWriteTime -Descending | Select-Object -First 1 +if (-not $report -and $reports.Count -eq 1) { + $report = $reports[0] +} +if (-not $report) { + throw "Expected one merged Cobertura report in '$ResultsDirectory', found $($reports.Count) reports." +} + +[xml] $coverage = Get-Content -Path $report.FullName -Raw +$invariant = [cultureinfo]::InvariantCulture +$lineRate = [double]::Parse($coverage.coverage.'line-rate', $invariant) * 100 +$branchRate = [double]::Parse($coverage.coverage.'branch-rate', $invariant) * 100 + +Write-Host ([string]::Format($invariant, 'Coverage report: {0}', $report.FullName)) +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)) + exit 1 +} diff --git a/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs b/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs index 7fe1055..79a557f 100644 --- a/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs +++ b/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs @@ -43,6 +43,14 @@ public int ReadViewProperties() + (view.Architecture?.Length ?? 0) + (view.Mobile == false ? 1 : 0); } + [Benchmark] + public int ReadRawViewProperties() + { + HttpClientHintsView view = _headers.GetClientHintsView(); + return (view.UA?.Length ?? 0) + (view.RawPlatform?.Length ?? 0) + + (view.RawArchitecture?.Length ?? 0) + (view.Mobile == false ? 1 : 0); + } + [Benchmark] public ClientHints GetClientHintsFromHeaders() => _headers.GetClientHints(); diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs index 73b056b..117621d 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs @@ -33,13 +33,13 @@ public static HttpClientHints GetClientHints(this HttpContext context) } /// - /// Returns a zero-allocation view over the request headers for accessing Client Hints lazily. + /// Returns a view over the request headers for accessing Client Hints lazily. /// public static HttpClientHintsView GetClientHintsView(this HttpContext context) => new(context.Request.Headers); /// - /// Returns a zero-allocation view over the provided headers for accessing Client Hints lazily. + /// Returns a view over the provided headers for accessing Client Hints lazily. /// public static HttpClientHintsView GetClientHintsView(this IHeaderDictionary headers) => new(headers); @@ -51,7 +51,6 @@ public static HttpClientHintsView GetClientHintsView(this IHeaderDictionary head /// An instance of populated with the relevant header values. public static HttpClientHints GetClientHints(this IHeaderDictionary headers) { - // Use the non-allocating view to gather values and build a snapshot. HttpClientHintsView view = new(headers); return view.BuildSnapshot(); } diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs index a4e1ac5..2196690 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs @@ -1,16 +1,17 @@ // Copyright © https://myCSharp.de - all rights reserved +using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; namespace MyCSharp.HttpClientHints.AspNetCore; /// -/// A zero-allocation view over to access HTTP Client Hints lazily. +/// A view over to access HTTP Client Hints lazily. /// /// -/// This struct does not allocate and reads values directly from the underlying request headers on demand. -/// Use to materialize a heap-allocated record if needed. +/// Creating the view and reading raw values do not allocate. Reading a decoded quoted value can allocate a string. +/// Use to capture raw and decoded values in a record. /// /// /// Creates a new view over the given headers. @@ -28,20 +29,52 @@ public string? UserAgent public string? UA => GetFirstValue("Sec-CH-UA"); - /// Sec-CH-UA-Platform + /// Gets the decoded Sec-CH-UA-Platform value. + /// + /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is + /// missing, the quoted value is malformed, or the value has parameters. + /// public string? Platform + => DecodeString(RawPlatform); + + /// Gets the original Sec-CH-UA-Platform value, including any quotes and escapes. + public string? RawPlatform => GetFirstValue("Sec-CH-UA-Platform"); - /// Sec-CH-UA-Platform-Version + /// Gets the decoded Sec-CH-UA-Platform-Version value. + /// + /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is + /// missing, the quoted value is malformed, or the value has parameters. + /// public string? PlatformVersion + => DecodeString(RawPlatformVersion); + + /// Gets the original Sec-CH-UA-Platform-Version value, including any quotes and escapes. + public string? RawPlatformVersion => GetFirstValue("Sec-CH-UA-Platform-Version"); - /// Sec-CH-UA-Arch + /// Gets the decoded Sec-CH-UA-Arch value. + /// + /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is + /// missing, the quoted value is malformed, or the value has parameters. + /// public string? Architecture + => DecodeString(RawArchitecture); + + /// Gets the original Sec-CH-UA-Arch value, including any quotes and escapes. + public string? RawArchitecture => GetFirstValue("Sec-CH-UA-Arch"); - /// Sec-CH-UA-Model + /// Gets the decoded Sec-CH-UA-Model value. + /// + /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is + /// missing, the quoted value is malformed, or the value has parameters. + /// public string? Model + => DecodeString(RawModel); + + /// Gets the original Sec-CH-UA-Model value, including any quotes and escapes. + public string? RawModel => GetFirstValue("Sec-CH-UA-Model"); /// Sec-CH-UA-Full-Version-List @@ -53,11 +86,66 @@ public bool? Mobile => HttpClientHintsInterpreter.IsMobile(GetFirstValue("Sec-CH-UA-Mobile")); /// - /// Materializes a snapshot record of the current values. This allocates one object. + /// Materializes a snapshot record of the current raw and decoded values. /// public HttpClientHints BuildSnapshot() - => new(UserAgent, Platform, PlatformVersion, Architecture, Model, FullVersionList, UA, Mobile, headers); + { + string? rawPlatform = RawPlatform; + string? rawPlatformVersion = RawPlatformVersion; + string? rawArchitecture = RawArchitecture; + string? rawModel = RawModel; + + return new HttpClientHints(UserAgent, DecodeString(rawPlatform), DecodeString(rawPlatformVersion), + DecodeString(rawArchitecture), DecodeString(rawModel), FullVersionList, UA, Mobile, headers) + { + RawPlatform = rawPlatform, + RawPlatformVersion = rawPlatformVersion, + RawArchitecture = rawArchitecture, + RawModel = rawModel + }; + } private string? GetFirstValue(string key) => headers.TryGetValue(key, out StringValues values) && values.Count > 0 ? values[0] : null; + + private static string? DecodeString(string? rawValue) + { + ReadOnlySpan value = rawValue.AsSpan().Trim(" \t"); + if (value.IsEmpty || value[0] != '"') + { + return rawValue; + } + + if (value.Length < 2 || value[^1] != '"') + { + return null; + } + + // RFC 9651 section 4.2.5 defines the quoted string and its two permitted escapes. + ReadOnlySpan content = value[1..^1]; + StringBuilder? decoded = null; + for (int index = 0; index < content.Length; index++) + { + char character = content[index]; + if (character == '\\') + { + int escapeIndex = index++; + if (index == content.Length || content[index] is not ('"' or '\\')) + { + return null; + } + + decoded ??= new StringBuilder(content.Length).Append(content[..escapeIndex]); + character = content[index]; + } + else if (character is '"' or < ' ' or > '~') + { + return null; + } + + decoded?.Append(character); + } + + return decoded?.ToString() ?? content.ToString(); + } } diff --git a/src/HttpClientHints.AspNetCore/readme.md b/src/HttpClientHints.AspNetCore/readme.md index 87cf5e0..f9baabd 100644 --- a/src/HttpClientHints.AspNetCore/readme.md +++ b/src/HttpClientHints.AspNetCore/readme.md @@ -2,4 +2,6 @@ Read HTTP Client Hints with .NET +In 4.0, `Platform`, `PlatformVersion`, `Architecture`, and `Model` return decoded strings. Use the matching `Raw*` properties to get the original header values. [Upgrade guide](https://github.com/mycsharp/HttpClientHints#upgrading-to-40) + https://github.com/mycsharp/HttpClientHints diff --git a/src/HttpClientHints/HttpClientHints.cs b/src/HttpClientHints/HttpClientHints.cs index 9dcea56..a01cd12 100644 --- a/src/HttpClientHints/HttpClientHints.cs +++ b/src/HttpClientHints/HttpClientHints.cs @@ -10,13 +10,32 @@ namespace MyCSharp.HttpClientHints; /// Represents HTTP Client Hints retrieved from the request headers. /// /// The User-Agent string from the request headers. -/// The platform information from the Sec-CH-UA-Platform header. -/// The version of the platform from the Sec-CH-UA-Platform-Version header. -/// The architecture from the Sec-CH-UA-Arch header. -/// The device model from the Sec-CH-UA-Model header. +/// The decoded platform from the Sec-CH-UA-Platform header. +/// The decoded platform version from the Sec-CH-UA-Platform-Version header. +/// The decoded architecture from the Sec-CH-UA-Arch header. +/// The decoded device model from the Sec-CH-UA-Model header. /// The full version list from the Sec-CH-UA-Full-Version-List header. /// The value of the Sec-CH-UA header. /// A nullable boolean indicating whether the device is mobile, derived from the Sec-CH-UA-Mobile header. /// The original headers dictionary containing all the request headers. +/// +/// When MyCSharp.HttpClientHints.AspNetCore creates this record, , , +/// , and contain decoded strings. They are if the +/// quoted value is malformed or has parameters. The Raw* properties keep the original header values. +/// A with expression that changes a decoded property does not change the matching Raw* property. +/// public record class HttpClientHints(string? UserAgent, string? Platform, string? PlatformVersion, - string? Architecture, string? Model, string? FullVersionList, string? UA, bool? Mobile, IDictionary Headers); + string? Architecture, string? Model, string? FullVersionList, string? UA, bool? Mobile, IDictionary Headers) +{ + /// Gets the original Sec-CH-UA-Platform value, including any quotes and escapes. + public string? RawPlatform { get; init; } + + /// Gets the original Sec-CH-UA-Platform-Version value, including any quotes and escapes. + public string? RawPlatformVersion { get; init; } + + /// Gets the original Sec-CH-UA-Arch value, including any quotes and escapes. + public string? RawArchitecture { get; init; } + + /// Gets the original Sec-CH-UA-Model value, including any quotes and escapes. + public string? RawModel { get; init; } +} diff --git a/src/HttpClientHints/readme.md b/src/HttpClientHints/readme.md index 87cf5e0..e503210 100644 --- a/src/HttpClientHints/readme.md +++ b/src/HttpClientHints/readme.md @@ -2,4 +2,6 @@ Read HTTP Client Hints with .NET +In 4.0, the `HttpClientHints` record has `RawPlatform`, `RawPlatformVersion`, `RawArchitecture`, and `RawModel` properties for the original header values. [Upgrade guide](https://github.com/mycsharp/HttpClientHints#upgrading-to-40) + https://github.com/mycsharp/HttpClientHints diff --git a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs index 44687e1..146ea21 100644 --- a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs +++ b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs @@ -15,13 +15,13 @@ public void GetClientHints_ReturnsCorrectValues_WhenHeadersArePresent() HeaderDictionary headers = new() { { "User-Agent", new StringValues("TestUserAgent") }, - { "Sec-CH-UA", new StringValues("TestUA") }, - { "Sec-CH-UA-Platform", new StringValues("TestPlatform") }, - { "Sec-CH-UA-Platform-Version", new StringValues("1.0") }, - { "Sec-CH-UA-Arch", new StringValues("x64") }, + { "Sec-CH-UA", new StringValues("\"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"") }, + { "Sec-CH-UA-Platform", new StringValues("\"Windows\"") }, + { "Sec-CH-UA-Platform-Version", new StringValues("\"19.0.0\"") }, + { "Sec-CH-UA-Arch", new StringValues("\"x86\"") }, { "Sec-CH-UA-Bitness", new StringValues("64") }, - { "Sec-CH-UA-Full-Version-List", new StringValues("1.0.0.0") }, - { "Sec-CH-UA-Model", new StringValues("TestModel") }, + { "Sec-CH-UA-Full-Version-List", new StringValues("\"Chromium\";v=\"138.0.7204.97\"") }, + { "Sec-CH-UA-Model", new StringValues("\"\"") }, { "Sec-CH-UA-Mobile", new StringValues("?1") } }; @@ -30,12 +30,16 @@ public void GetClientHints_ReturnsCorrectValues_WhenHeadersArePresent() // Assert Assert.Equal("TestUserAgent", clientHints.UserAgent); - Assert.Equal("TestPlatform", clientHints.Platform); - Assert.Equal("1.0", clientHints.PlatformVersion); - Assert.Equal("x64", clientHints.Architecture); - Assert.Equal("TestModel", clientHints.Model); - Assert.Equal("1.0.0.0", clientHints.FullVersionList); - Assert.Equal("TestUA", clientHints.UA); + Assert.Equal("Windows", clientHints.Platform); + Assert.Equal("\"Windows\"", clientHints.RawPlatform); + Assert.Equal("19.0.0", clientHints.PlatformVersion); + Assert.Equal("\"19.0.0\"", clientHints.RawPlatformVersion); + Assert.Equal("x86", clientHints.Architecture); + Assert.Equal("\"x86\"", clientHints.RawArchitecture); + Assert.Equal(string.Empty, clientHints.Model); + Assert.Equal("\"\"", clientHints.RawModel); + Assert.Equal("\"Chromium\";v=\"138.0.7204.97\"", clientHints.FullVersionList); + Assert.Equal("\"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"", clientHints.UA); Assert.True(clientHints.Mobile); Assert.Equal(headers, clientHints.Headers); } @@ -52,15 +56,81 @@ public void GetClientHints_ReturnsNullValues_WhenHeadersAreMissing() // Assert Assert.Null(clientHints.UserAgent); Assert.Null(clientHints.Platform); + Assert.Null(clientHints.RawPlatform); Assert.Null(clientHints.PlatformVersion); + Assert.Null(clientHints.RawPlatformVersion); Assert.Null(clientHints.Architecture); + Assert.Null(clientHints.RawArchitecture); Assert.Null(clientHints.Model); + Assert.Null(clientHints.RawModel); Assert.Null(clientHints.FullVersionList); Assert.Null(clientHints.UA); Assert.Null(clientHints.Mobile); Assert.Equal(headers, clientHints.Headers); } + [Theory] + [InlineData(null, null)] + [InlineData("", "")] + [InlineData("legacy unquoted value", "legacy unquoted value")] + [InlineData("\"\"", "")] + [InlineData(" \t\"model\"\t ", "model")] + [InlineData("\" model \"", " model ")] + [InlineData("\"Model \\\"Pro\\\" \\\\ Edition\"", "Model \"Pro\" \\ Edition")] + [InlineData("\"Model", null)] + [InlineData("\"Model\" suffix", null)] + [InlineData("\"Model\\\"", null)] + [InlineData("\"Model\\q\"", null)] + [InlineData("\"Model\" \"Pro\"", null)] + [InlineData("\"Model\tPro\"", null)] + [InlineData("\"Modèle\"", null)] + [InlineData(" ", " ")] + [InlineData("\"", null)] + [InlineData("\"\\\\\"", "\\")] + [InlineData("\" !#[]~\"", " !#[]~")] + [InlineData("\"Model\u007F\"", null)] + [InlineData("\"Model\";v=1", null)] + public void GetClientHints_ExposesDecodedAndRawStructuredStrings(string? rawModel, string? model) + { + HeaderDictionary headers = []; + if (rawModel is not null) + { + headers["Sec-CH-UA-Model"] = rawModel; + } + + HttpClientHintsView view = headers.GetClientHintsView(); + HttpClientHints snapshot = headers.GetClientHints(); + + Assert.Equal(model, view.Model); + Assert.Equal(rawModel, view.RawModel); + Assert.Equal(model, snapshot.Model); + Assert.Equal(rawModel, snapshot.RawModel); + } + + [Fact] + public void GetClientHintsView_DecodesEveryStructuredStringHeader() + { + HeaderDictionary headers = new() + { + ["Sec-CH-UA-Platform"] = "\"Windows\"", + ["Sec-CH-UA-Platform-Version"] = "\"19.0.0\"", + ["Sec-CH-UA-Arch"] = "\"arm\"", + ["Sec-CH-UA-Model"] = "\"Pixel \\\"9\\\"\"" + }; + + HttpClientHintsView view = headers.GetClientHintsView(); + + Assert.Same(headers, view.Headers); + Assert.Equal("Windows", view.Platform); + Assert.Equal("\"Windows\"", view.RawPlatform); + Assert.Equal("19.0.0", view.PlatformVersion); + Assert.Equal("\"19.0.0\"", view.RawPlatformVersion); + Assert.Equal("arm", view.Architecture); + Assert.Equal("\"arm\"", view.RawArchitecture); + Assert.Equal("Pixel \"9\"", view.Model); + Assert.Equal("\"Pixel \\\"9\\\"\"", view.RawModel); + } + [Fact] public void GetClientHints_ReturnsCorrectMobileValue_WhenMobileHeaderIsTrue() { @@ -122,6 +192,7 @@ public void GetClientHintsView_UsesOnlyTheFirstValue() Assert.Equal("first", view.UA); Assert.False(view.Mobile); Assert.Null(view.Platform); + Assert.Null(view.RawPlatform); Assert.Equal(string.Empty, view.Model); } @@ -130,14 +201,21 @@ public void GetClientHints_ReusesSnapshotForTheSameContext() { DefaultHttpContext context = new(); context.Request.Headers["Sec-CH-UA"] = "original"; + context.Request.Headers["Sec-CH-UA-Platform"] = "\"Windows\""; context.Items["__HttpClientHints"] = "application data"; HttpClientHints snapshot = context.GetClientHints(); context.Request.Headers["Sec-CH-UA"] = "updated"; + context.Request.Headers["Sec-CH-UA-Platform"] = "\"Linux\""; Assert.Equal("original", snapshot.UA); + Assert.Equal("Windows", snapshot.Platform); + Assert.Equal("\"Windows\"", snapshot.RawPlatform); Assert.Same(snapshot, context.GetClientHints()); - Assert.Equal("updated", context.GetClientHintsView().UA); + HttpClientHintsView view = context.GetClientHintsView(); + Assert.Equal("updated", view.UA); + Assert.Equal("Linux", view.Platform); + Assert.Equal("\"Linux\"", view.RawPlatform); Assert.Equal("application data", context.Items["__HttpClientHints"]); } } diff --git a/version.json b/version.json index 72f7505..5e0bc01 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.1", + "version": "4.0", "nugetPackageVersion": { "semVer": 1 // optional. Set to either 1 or 2 to control how the NuGet package version string is generated. Default is 1. }, From 92fb22219ec7fccd47f73a58c7cafbcd509895bb Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sat, 21 Nov 2026 15:53:08 +0100 Subject: [PATCH 2/3] feat: keep header values, add lazily decoded Decoded* properties - Platform, PlatformVersion, Architecture, and Model return the header values as sent again, as in 3.x, so the change is no longer breaking - Add DecodedPlatform, DecodedPlatformVersion, DecodedArchitecture, and DecodedModel to HttpClientHints and HttpClientHintsView; they decode on every access and store nothing - Move the decoder to the public HttpClientHintsInterpreter.DecodeStructuredString - Remove the Raw* properties and set the version to 3.2 instead of 4.0 - Replace the upgrade guide with a "Decoded values" README section - Benchmark decoded reads with ReadDecodedViewProperties --- README.md | 46 +++---- .../HttpClientHintBenchmarks.cs | 6 +- .../HttpClientHintsHttpContextExtensions.cs | 5 +- .../HttpClientHintsView.cs | 125 ++++-------------- src/HttpClientHints.AspNetCore/readme.md | 2 +- src/HttpClientHints/HttpClientHints.cs | 34 ++--- .../HttpClientHintsInterpreter.cs | 58 ++++++++ src/HttpClientHints/readme.md | 2 +- ...tpClientHintsHttpContextExtensionsTests.cs | 79 +++++------ .../HttpClientHintsInterpreterTests.cs | 37 ++++++ .../HttpClientHintsTests.cs | 61 +++++++++ version.json | 2 +- 12 files changed, 268 insertions(+), 189 deletions(-) create mode 100644 tests/HttpClientHints.UnitTests/HttpClientHintsTests.cs diff --git a/README.md b/README.md index 4403a80..fa8092a 100644 --- a/README.md +++ b/README.md @@ -57,28 +57,28 @@ HttpClientHints clientHints = HttpClientHintsHttpContextExtensions.GetClientHint Since potentially all client hints are optional, all properties are potentially nullable, which means that the client has not provided this data. -## Upgrading to 4.0 +## Decoded values -**Breaking change.** Version 4.0 changes what four properties return when Client Hints are read through `GetClientHints()` or `GetClientHintsView()`. They now decode the HTTP Structured Field string. To keep using the original value as returned in 3.x, switch to the corresponding `Raw*` property. +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. -| Decoded property | Raw property | Request header | +| Request header | Property | Decoded property | | --- | --- | --- | -| `Platform` | `RawPlatform` | `Sec-CH-UA-Platform` | -| `PlatformVersion` | `RawPlatformVersion` | `Sec-CH-UA-Platform-Version` | -| `Architecture` | `RawArchitecture` | `Sec-CH-UA-Arch` | -| `Model` | `RawModel` | `Sec-CH-UA-Model` | - -For a request with `Sec-CH-UA-Platform: "Windows"`, both forms are available. +| `Sec-CH-UA-Platform` | `Platform` | `DecodedPlatform` | +| `Sec-CH-UA-Platform-Version` | `PlatformVersion` | `DecodedPlatformVersion` | +| `Sec-CH-UA-Arch` | `Architecture` | `DecodedArchitecture` | +| `Sec-CH-UA-Model` | `Model` | `DecodedModel` | ```csharp HttpClientHints hints = httpContext.GetClientHints(); -bool isWindows = hints.Platform == "Windows"; -string? originalPlatformHeader = hints.RawPlatform; // Contains the two quote characters. +string? platformHeader = hints.Platform; // "Windows", including the two quote characters +bool isWindows = hints.DecodedPlatform == "Windows"; ``` -An absent header yields `null` for both properties. A quoted empty value such as `Sec-CH-UA-Model: ""` decodes to `string.Empty`. Unquoted values pass through as supplied. A malformed quoted value yields `null` in the decoded property and remains available in the raw property. Parameters are not supported: `Sec-CH-UA-Platform: "Windows";a=1` also yields `null` in the decoded property. [RFC 9651 § 4.2.5](https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.5) +The `Decoded*` properties are available on `HttpClientHints` and `HttpClientHintsView`. They decode the value on every access and store nothing, so reading `Platform` or building a snapshot costs nothing extra. Store the decoded value in a local variable if you need it more than once. `HttpClientHintsInterpreter.DecodeStructuredString` decodes any other header value of this type. + +An absent header yields `null`. A quoted empty value such as `Sec-CH-UA-Model: ""` decodes to `string.Empty`. Unquoted values pass through as supplied. A malformed quoted value yields `null`. Parameters are not supported: `Sec-CH-UA-Platform: "Windows";a=1` also yields `null`. [RFC 9651 § 4.2.5](https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.5) -`UA` and `FullVersionList` expose serialized brand lists. The `Headers` collection provides access to all original header values. If you construct an `HttpClientHints` record directly, supply the decoded values to its constructor and set the raw properties in an object initializer when you have the original values. A `with` expression that changes a decoded property, such as `hints with { Platform = "Linux" }`, leaves the matching `Raw*` property unchanged. +`UA` and `FullVersionList` expose serialized brand lists. The `Headers` collection provides access to all original header values. ## Customization @@ -118,12 +118,12 @@ Line and branch coverage must stay at or above 90 %. CI collects coverage on eve ## Benchmark -Reading `Raw*` properties from the view does not allocate. Reading a decoded property allocates the decoded string, and a snapshot stores both forms. Run the benchmarks with `dotnet run -c Release --project perf/HttpClientHints.Benchmarks --framework net11.0 -- --filter '*' --iterationCount 15 --iterationTime 200 --launchCount 2 --warmupCount 6`. +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`. ``` 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, 21,42 GB Available +Memory: 61,64 GB Total, 31,05 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 @@ -132,14 +132,14 @@ IterationCount=15 IterationTime=200ms LaunchCount=2 WarmupCount=6 ``` -| Method | Mean | Error | StdDev | Median | Gen0 | Allocated | -|-------------------------------------- |-----------:|----------:|----------:|-----------:|-------:|----------:| -| ReadViewProperties | 38.403 ns | 1.2810 ns | 1.8777 ns | 37.723 ns | 0.0042 | 72 B | -| ReadRawViewProperties | 19.796 ns | 0.5348 ns | 0.7671 ns | 19.829 ns | - | - | -| GetClientHintsFromHeaders | 96.731 ns | 2.1783 ns | 3.1241 ns | 96.137 ns | 0.0134 | 232 B | -| GetClientHintsFromHeadersWithoutHints | 61.318 ns | 1.8116 ns | 2.6554 ns | 59.624 ns | 0.0072 | 120 B | -| GetClientHintsFromContextUncached | 108.202 ns | 1.5130 ns | 2.0709 ns | 108.719 ns | 0.0136 | 232 B | -| GetClientHintsFromContextCached | 6.524 ns | 0.0837 ns | 0.1227 ns | 6.510 ns | - | - | +| 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 | - | - | ## Samples diff --git a/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs b/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs index 79a557f..e9a7c0a 100644 --- a/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs +++ b/perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs @@ -44,11 +44,11 @@ public int ReadViewProperties() } [Benchmark] - public int ReadRawViewProperties() + public int ReadDecodedViewProperties() { HttpClientHintsView view = _headers.GetClientHintsView(); - return (view.UA?.Length ?? 0) + (view.RawPlatform?.Length ?? 0) - + (view.RawArchitecture?.Length ?? 0) + (view.Mobile == false ? 1 : 0); + return (view.UA?.Length ?? 0) + (view.DecodedPlatform?.Length ?? 0) + + (view.DecodedArchitecture?.Length ?? 0) + (view.Mobile == false ? 1 : 0); } [Benchmark] diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs index 117621d..73b056b 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs @@ -33,13 +33,13 @@ public static HttpClientHints GetClientHints(this HttpContext context) } /// - /// Returns a view over the request headers for accessing Client Hints lazily. + /// Returns a zero-allocation view over the request headers for accessing Client Hints lazily. /// public static HttpClientHintsView GetClientHintsView(this HttpContext context) => new(context.Request.Headers); /// - /// Returns a view over the provided headers for accessing Client Hints lazily. + /// Returns a zero-allocation view over the provided headers for accessing Client Hints lazily. /// public static HttpClientHintsView GetClientHintsView(this IHeaderDictionary headers) => new(headers); @@ -51,6 +51,7 @@ public static HttpClientHintsView GetClientHintsView(this IHeaderDictionary head /// An instance of populated with the relevant header values. public static HttpClientHints GetClientHints(this IHeaderDictionary headers) { + // Use the non-allocating view to gather values and build a snapshot. HttpClientHintsView view = new(headers); return view.BuildSnapshot(); } diff --git a/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs b/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs index 2196690..15c00bd 100644 --- a/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs +++ b/src/HttpClientHints.AspNetCore/HttpClientHintsView.cs @@ -1,6 +1,5 @@ // Copyright © https://myCSharp.de - all rights reserved -using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; @@ -10,8 +9,9 @@ namespace MyCSharp.HttpClientHints.AspNetCore; /// A view over to access HTTP Client Hints lazily. /// /// -/// Creating the view and reading raw values do not allocate. Reading a decoded quoted value can allocate a string. -/// Use to capture raw and decoded values in a record. +/// Creating the view and reading header values do not allocate. The Decoded* properties decode the value on +/// every access and allocate the decoded string for a quoted value. +/// Use to materialize a heap-allocated record if needed. /// /// /// Creates a new view over the given headers. @@ -29,54 +29,42 @@ public string? UserAgent public string? UA => GetFirstValue("Sec-CH-UA"); - /// Gets the decoded Sec-CH-UA-Platform value. - /// - /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is - /// missing, the quoted value is malformed, or the value has parameters. - /// + /// Sec-CH-UA-Platform as sent, including quotes. returns it without quotes. public string? Platform - => DecodeString(RawPlatform); - - /// Gets the original Sec-CH-UA-Platform value, including any quotes and escapes. - public string? RawPlatform => GetFirstValue("Sec-CH-UA-Platform"); - /// Gets the decoded Sec-CH-UA-Platform-Version value. - /// - /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is - /// missing, the quoted value is malformed, or the value has parameters. - /// - public string? PlatformVersion - => DecodeString(RawPlatformVersion); + /// Gets decoded, for example Windows instead of "Windows". + /// The decoded value, or as described in . + public string? DecodedPlatform + => HttpClientHintsInterpreter.DecodeStructuredString(Platform); - /// Gets the original Sec-CH-UA-Platform-Version value, including any quotes and escapes. - public string? RawPlatformVersion + /// Sec-CH-UA-Platform-Version as sent, including quotes. returns it without quotes. + public string? PlatformVersion => GetFirstValue("Sec-CH-UA-Platform-Version"); - /// Gets the decoded Sec-CH-UA-Arch value. - /// - /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is - /// missing, the quoted value is malformed, or the value has parameters. - /// - public string? Architecture - => DecodeString(RawArchitecture); + /// Gets decoded, for example 19.0.0 instead of "19.0.0". + /// The decoded value, or as described in . + public string? DecodedPlatformVersion + => HttpClientHintsInterpreter.DecodeStructuredString(PlatformVersion); - /// Gets the original Sec-CH-UA-Arch value, including any quotes and escapes. - public string? RawArchitecture + /// Sec-CH-UA-Arch as sent, including quotes. returns it without quotes. + public string? Architecture => GetFirstValue("Sec-CH-UA-Arch"); - /// Gets the decoded Sec-CH-UA-Model value. - /// - /// The unescaped content of a quoted value, an unquoted value as sent, or if the header is - /// missing, the quoted value is malformed, or the value has parameters. - /// - public string? Model - => DecodeString(RawModel); + /// Gets decoded, for example x86 instead of "x86". + /// The decoded value, or as described in . + public string? DecodedArchitecture + => HttpClientHintsInterpreter.DecodeStructuredString(Architecture); - /// Gets the original Sec-CH-UA-Model value, including any quotes and escapes. - public string? RawModel + /// Sec-CH-UA-Model as sent, including quotes. returns it without quotes. + public string? Model => GetFirstValue("Sec-CH-UA-Model"); + /// Gets decoded, for example Pixel 9 instead of "Pixel 9". + /// The decoded value, or as described in . + public string? DecodedModel + => HttpClientHintsInterpreter.DecodeStructuredString(Model); + /// Sec-CH-UA-Full-Version-List public string? FullVersionList => GetFirstValue("Sec-CH-UA-Full-Version-List"); @@ -86,66 +74,11 @@ public bool? Mobile => HttpClientHintsInterpreter.IsMobile(GetFirstValue("Sec-CH-UA-Mobile")); /// - /// Materializes a snapshot record of the current raw and decoded values. + /// Materializes a snapshot record of the current values. This allocates one object. /// public HttpClientHints BuildSnapshot() - { - string? rawPlatform = RawPlatform; - string? rawPlatformVersion = RawPlatformVersion; - string? rawArchitecture = RawArchitecture; - string? rawModel = RawModel; - - return new HttpClientHints(UserAgent, DecodeString(rawPlatform), DecodeString(rawPlatformVersion), - DecodeString(rawArchitecture), DecodeString(rawModel), FullVersionList, UA, Mobile, headers) - { - RawPlatform = rawPlatform, - RawPlatformVersion = rawPlatformVersion, - RawArchitecture = rawArchitecture, - RawModel = rawModel - }; - } + => new(UserAgent, Platform, PlatformVersion, Architecture, Model, FullVersionList, UA, Mobile, headers); private string? GetFirstValue(string key) => headers.TryGetValue(key, out StringValues values) && values.Count > 0 ? values[0] : null; - - private static string? DecodeString(string? rawValue) - { - ReadOnlySpan value = rawValue.AsSpan().Trim(" \t"); - if (value.IsEmpty || value[0] != '"') - { - return rawValue; - } - - if (value.Length < 2 || value[^1] != '"') - { - return null; - } - - // RFC 9651 section 4.2.5 defines the quoted string and its two permitted escapes. - ReadOnlySpan content = value[1..^1]; - StringBuilder? decoded = null; - for (int index = 0; index < content.Length; index++) - { - char character = content[index]; - if (character == '\\') - { - int escapeIndex = index++; - if (index == content.Length || content[index] is not ('"' or '\\')) - { - return null; - } - - decoded ??= new StringBuilder(content.Length).Append(content[..escapeIndex]); - character = content[index]; - } - else if (character is '"' or < ' ' or > '~') - { - return null; - } - - decoded?.Append(character); - } - - return decoded?.ToString() ?? content.ToString(); - } } diff --git a/src/HttpClientHints.AspNetCore/readme.md b/src/HttpClientHints.AspNetCore/readme.md index f9baabd..c484a2f 100644 --- a/src/HttpClientHints.AspNetCore/readme.md +++ b/src/HttpClientHints.AspNetCore/readme.md @@ -2,6 +2,6 @@ Read HTTP Client Hints with .NET -In 4.0, `Platform`, `PlatformVersion`, `Architecture`, and `Model` return decoded strings. Use the matching `Raw*` properties to get the original header values. [Upgrade guide](https://github.com/mycsharp/HttpClientHints#upgrading-to-40) +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) https://github.com/mycsharp/HttpClientHints diff --git a/src/HttpClientHints/HttpClientHints.cs b/src/HttpClientHints/HttpClientHints.cs index a01cd12..dbae8fb 100644 --- a/src/HttpClientHints/HttpClientHints.cs +++ b/src/HttpClientHints/HttpClientHints.cs @@ -10,32 +10,34 @@ namespace MyCSharp.HttpClientHints; /// Represents HTTP Client Hints retrieved from the request headers. /// /// The User-Agent string from the request headers. -/// The decoded platform from the Sec-CH-UA-Platform header. -/// The decoded platform version from the Sec-CH-UA-Platform-Version header. -/// The decoded architecture from the Sec-CH-UA-Arch header. -/// The decoded device model from the Sec-CH-UA-Model header. +/// The Sec-CH-UA-Platform header value as sent, including quotes. returns it without quotes. +/// The Sec-CH-UA-Platform-Version header value as sent, including quotes. returns it without quotes. +/// The Sec-CH-UA-Arch header value as sent, including quotes. returns it without quotes. +/// The Sec-CH-UA-Model header value as sent, including quotes. returns it without quotes. /// The full version list from the Sec-CH-UA-Full-Version-List header. /// The value of the Sec-CH-UA header. /// A nullable boolean indicating whether the device is mobile, derived from the Sec-CH-UA-Mobile header. /// The original headers dictionary containing all the request headers. /// -/// When MyCSharp.HttpClientHints.AspNetCore creates this record, , , -/// , and contain decoded strings. They are if the -/// quoted value is malformed or has parameters. The Raw* properties keep the original header values. -/// A with expression that changes a decoded property does not change the matching Raw* property. +/// The Decoded* properties decode the matching property with +/// on every access. They store nothing, so they are not part of record equality and follow with expressions. /// public record class HttpClientHints(string? UserAgent, string? Platform, string? PlatformVersion, string? Architecture, string? Model, string? FullVersionList, string? UA, bool? Mobile, IDictionary Headers) { - /// Gets the original Sec-CH-UA-Platform value, including any quotes and escapes. - public string? RawPlatform { get; init; } + /// Gets decoded, for example Windows instead of "Windows". + /// The decoded value, or as described in . + public string? DecodedPlatform => HttpClientHintsInterpreter.DecodeStructuredString(Platform); - /// Gets the original Sec-CH-UA-Platform-Version value, including any quotes and escapes. - public string? RawPlatformVersion { get; init; } + /// Gets decoded, for example 19.0.0 instead of "19.0.0". + /// The decoded value, or as described in . + public string? DecodedPlatformVersion => HttpClientHintsInterpreter.DecodeStructuredString(PlatformVersion); - /// Gets the original Sec-CH-UA-Arch value, including any quotes and escapes. - public string? RawArchitecture { get; init; } + /// Gets decoded, for example x86 instead of "x86". + /// The decoded value, or as described in . + public string? DecodedArchitecture => HttpClientHintsInterpreter.DecodeStructuredString(Architecture); - /// Gets the original Sec-CH-UA-Model value, including any quotes and escapes. - public string? RawModel { get; init; } + /// Gets decoded, for example Pixel 9 instead of "Pixel 9". + /// The decoded value, or as described in . + public string? DecodedModel => HttpClientHintsInterpreter.DecodeStructuredString(Model); } diff --git a/src/HttpClientHints/HttpClientHintsInterpreter.cs b/src/HttpClientHints/HttpClientHintsInterpreter.cs index ef8d77d..d0ce437 100644 --- a/src/HttpClientHints/HttpClientHintsInterpreter.cs +++ b/src/HttpClientHints/HttpClientHintsInterpreter.cs @@ -1,5 +1,7 @@ // Copyright © https://myCSharp.de - all rights reserved +using System.Text; + namespace MyCSharp.HttpClientHints; /// @@ -33,4 +35,60 @@ public static class HttpClientHintsInterpreter _ => null }; } + + /// + /// Decodes a header value that is an HTTP Structured Field string, such as Sec-CH-UA-Platform: "Windows". + /// + /// The header value as sent, for example "Windows" including the quotes. + /// + /// The decoded value: + /// + /// The content of a quoted value with the escapes \" and \\ resolved, for example Windows. + /// The value as sent if it is not quoted. + /// null if is null, the quoted value is malformed, or the value has parameters. + /// + /// + /// + /// Follows RFC 9651, section 4.2.5. Leading and trailing spaces and tabs are ignored. + /// A quoted value allocates a new string unless it is empty. + /// + public static string? DecodeStructuredString(string? headerValue) + { + ReadOnlySpan value = headerValue.AsSpan().Trim(" \t"); + if (value.IsEmpty || value[0] != '"') + { + return headerValue; + } + + if (value.Length < 2 || value[^1] != '"') + { + return null; + } + + ReadOnlySpan content = value[1..^1]; + StringBuilder? decoded = null; + for (int index = 0; index < content.Length; index++) + { + char character = content[index]; + if (character == '\\') + { + int escapeIndex = index++; + if (index == content.Length || content[index] is not ('"' or '\\')) + { + return null; + } + + decoded ??= new StringBuilder(content.Length).Append(content[..escapeIndex]); + character = content[index]; + } + else if (character is '"' or < ' ' or > '~') + { + return null; + } + + decoded?.Append(character); + } + + return decoded?.ToString() ?? content.ToString(); + } } diff --git a/src/HttpClientHints/readme.md b/src/HttpClientHints/readme.md index e503210..a023489 100644 --- a/src/HttpClientHints/readme.md +++ b/src/HttpClientHints/readme.md @@ -2,6 +2,6 @@ Read HTTP Client Hints with .NET -In 4.0, the `HttpClientHints` record has `RawPlatform`, `RawPlatformVersion`, `RawArchitecture`, and `RawModel` properties for the original header values. [Upgrade guide](https://github.com/mycsharp/HttpClientHints#upgrading-to-40) +Since 3.2, the `HttpClientHints` record has `DecodedPlatform`, `DecodedPlatformVersion`, `DecodedArchitecture`, and `DecodedModel` properties that return the header values without quotes, and `HttpClientHintsInterpreter.DecodeStructuredString` decodes other quoted header values. [Decoded values](https://github.com/mycsharp/HttpClientHints#decoded-values) https://github.com/mycsharp/HttpClientHints diff --git a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs index 146ea21..880530d 100644 --- a/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs +++ b/tests/HttpClientHints.AspNetCore.UnitTests/HttpClientHintsHttpContextExtensionsTests.cs @@ -30,14 +30,14 @@ public void GetClientHints_ReturnsCorrectValues_WhenHeadersArePresent() // Assert Assert.Equal("TestUserAgent", clientHints.UserAgent); - Assert.Equal("Windows", clientHints.Platform); - Assert.Equal("\"Windows\"", clientHints.RawPlatform); - Assert.Equal("19.0.0", clientHints.PlatformVersion); - Assert.Equal("\"19.0.0\"", clientHints.RawPlatformVersion); - Assert.Equal("x86", clientHints.Architecture); - Assert.Equal("\"x86\"", clientHints.RawArchitecture); - Assert.Equal(string.Empty, clientHints.Model); - Assert.Equal("\"\"", clientHints.RawModel); + Assert.Equal("\"Windows\"", clientHints.Platform); + Assert.Equal("Windows", clientHints.DecodedPlatform); + Assert.Equal("\"19.0.0\"", clientHints.PlatformVersion); + Assert.Equal("19.0.0", clientHints.DecodedPlatformVersion); + Assert.Equal("\"x86\"", clientHints.Architecture); + Assert.Equal("x86", clientHints.DecodedArchitecture); + Assert.Equal("\"\"", clientHints.Model); + Assert.Equal(string.Empty, clientHints.DecodedModel); Assert.Equal("\"Chromium\";v=\"138.0.7204.97\"", clientHints.FullVersionList); Assert.Equal("\"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"", clientHints.UA); Assert.True(clientHints.Mobile); @@ -56,13 +56,13 @@ public void GetClientHints_ReturnsNullValues_WhenHeadersAreMissing() // Assert Assert.Null(clientHints.UserAgent); Assert.Null(clientHints.Platform); - Assert.Null(clientHints.RawPlatform); + Assert.Null(clientHints.DecodedPlatform); Assert.Null(clientHints.PlatformVersion); - Assert.Null(clientHints.RawPlatformVersion); + Assert.Null(clientHints.DecodedPlatformVersion); Assert.Null(clientHints.Architecture); - Assert.Null(clientHints.RawArchitecture); + Assert.Null(clientHints.DecodedArchitecture); Assert.Null(clientHints.Model); - Assert.Null(clientHints.RawModel); + Assert.Null(clientHints.DecodedModel); Assert.Null(clientHints.FullVersionList); Assert.Null(clientHints.UA); Assert.Null(clientHints.Mobile); @@ -71,40 +71,26 @@ public void GetClientHints_ReturnsNullValues_WhenHeadersAreMissing() [Theory] [InlineData(null, null)] - [InlineData("", "")] [InlineData("legacy unquoted value", "legacy unquoted value")] [InlineData("\"\"", "")] - [InlineData(" \t\"model\"\t ", "model")] - [InlineData("\" model \"", " model ")] [InlineData("\"Model \\\"Pro\\\" \\\\ Edition\"", "Model \"Pro\" \\ Edition")] [InlineData("\"Model", null)] - [InlineData("\"Model\" suffix", null)] - [InlineData("\"Model\\\"", null)] - [InlineData("\"Model\\q\"", null)] - [InlineData("\"Model\" \"Pro\"", null)] - [InlineData("\"Model\tPro\"", null)] - [InlineData("\"Modèle\"", null)] - [InlineData(" ", " ")] - [InlineData("\"", null)] - [InlineData("\"\\\\\"", "\\")] - [InlineData("\" !#[]~\"", " !#[]~")] - [InlineData("\"Model\u007F\"", null)] [InlineData("\"Model\";v=1", null)] - public void GetClientHints_ExposesDecodedAndRawStructuredStrings(string? rawModel, string? model) + public void GetClientHints_KeepsHeaderValueAndDecodesOnDemand(string? headerValue, string? decodedValue) { HeaderDictionary headers = []; - if (rawModel is not null) + if (headerValue is not null) { - headers["Sec-CH-UA-Model"] = rawModel; + headers["Sec-CH-UA-Model"] = headerValue; } HttpClientHintsView view = headers.GetClientHintsView(); HttpClientHints snapshot = headers.GetClientHints(); - Assert.Equal(model, view.Model); - Assert.Equal(rawModel, view.RawModel); - Assert.Equal(model, snapshot.Model); - Assert.Equal(rawModel, snapshot.RawModel); + Assert.Equal(headerValue, view.Model); + Assert.Equal(decodedValue, view.DecodedModel); + Assert.Equal(headerValue, snapshot.Model); + Assert.Equal(decodedValue, snapshot.DecodedModel); } [Fact] @@ -121,14 +107,14 @@ public void GetClientHintsView_DecodesEveryStructuredStringHeader() HttpClientHintsView view = headers.GetClientHintsView(); Assert.Same(headers, view.Headers); - Assert.Equal("Windows", view.Platform); - Assert.Equal("\"Windows\"", view.RawPlatform); - Assert.Equal("19.0.0", view.PlatformVersion); - Assert.Equal("\"19.0.0\"", view.RawPlatformVersion); - Assert.Equal("arm", view.Architecture); - Assert.Equal("\"arm\"", view.RawArchitecture); - Assert.Equal("Pixel \"9\"", view.Model); - Assert.Equal("\"Pixel \\\"9\\\"\"", view.RawModel); + Assert.Equal("\"Windows\"", view.Platform); + Assert.Equal("Windows", view.DecodedPlatform); + Assert.Equal("\"19.0.0\"", view.PlatformVersion); + Assert.Equal("19.0.0", view.DecodedPlatformVersion); + Assert.Equal("\"arm\"", view.Architecture); + Assert.Equal("arm", view.DecodedArchitecture); + Assert.Equal("\"Pixel \\\"9\\\"\"", view.Model); + Assert.Equal("Pixel \"9\"", view.DecodedModel); } [Fact] @@ -192,8 +178,9 @@ public void GetClientHintsView_UsesOnlyTheFirstValue() Assert.Equal("first", view.UA); Assert.False(view.Mobile); Assert.Null(view.Platform); - Assert.Null(view.RawPlatform); + Assert.Null(view.DecodedPlatform); Assert.Equal(string.Empty, view.Model); + Assert.Equal(string.Empty, view.DecodedModel); } [Fact] @@ -209,13 +196,13 @@ public void GetClientHints_ReusesSnapshotForTheSameContext() context.Request.Headers["Sec-CH-UA-Platform"] = "\"Linux\""; Assert.Equal("original", snapshot.UA); - Assert.Equal("Windows", snapshot.Platform); - Assert.Equal("\"Windows\"", snapshot.RawPlatform); + Assert.Equal("\"Windows\"", snapshot.Platform); + Assert.Equal("Windows", snapshot.DecodedPlatform); Assert.Same(snapshot, context.GetClientHints()); HttpClientHintsView view = context.GetClientHintsView(); Assert.Equal("updated", view.UA); - Assert.Equal("Linux", view.Platform); - Assert.Equal("\"Linux\"", view.RawPlatform); + Assert.Equal("\"Linux\"", view.Platform); + Assert.Equal("Linux", view.DecodedPlatform); Assert.Equal("application data", context.Items["__HttpClientHints"]); } } diff --git a/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs b/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs index 9f2e769..444ffea 100644 --- a/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs +++ b/tests/HttpClientHints.UnitTests/HttpClientHintsInterpreterTests.cs @@ -26,4 +26,41 @@ public void IsMobile_ShouldReturnExpectedResult_ForGivenInput(string? input, boo // Assert Assert.Equal(expectedResult, result); } + + [Theory] + [InlineData(null, null)] + [InlineData("", "")] + [InlineData(" ", " ")] + [InlineData("legacy unquoted value", "legacy unquoted value")] + [InlineData("\"\"", "")] + [InlineData("\"Windows\"", "Windows")] + [InlineData(" \t\"model\"\t ", "model")] + [InlineData("\" model \"", " model ")] + [InlineData("\"Model \\\"Pro\\\" \\\\ Edition\"", "Model \"Pro\" \\ Edition")] + [InlineData("\"\\\\\"", "\\")] + [InlineData("\" !#[]~\"", " !#[]~")] + [InlineData("\"", null)] + [InlineData("\"Model", null)] + [InlineData("\"Model\" suffix", null)] + [InlineData("\"Model\\\"", null)] + [InlineData("\"Model\\q\"", null)] + [InlineData("\"Model\" \"Pro\"", null)] + [InlineData("\"Model\tPro\"", null)] + [InlineData("\"Model\u007F\"", null)] + [InlineData("\"Modèle\"", null)] + [InlineData("\"Model\";v=1", null)] + public void DecodeStructuredString_ShouldReturnExpectedResult_ForGivenInput(string? input, string? expectedResult) + { + string? result = HttpClientHintsInterpreter.DecodeStructuredString(input); + + Assert.Equal(expectedResult, result); + } + + [Fact] + public void DecodeStructuredString_ReturnsTheSameInstance_ForUnquotedValues() + { + string unquoted = "Windows"; + + Assert.Same(unquoted, HttpClientHintsInterpreter.DecodeStructuredString(unquoted)); + } } diff --git a/tests/HttpClientHints.UnitTests/HttpClientHintsTests.cs b/tests/HttpClientHints.UnitTests/HttpClientHintsTests.cs new file mode 100644 index 0000000..d553a5f --- /dev/null +++ b/tests/HttpClientHints.UnitTests/HttpClientHintsTests.cs @@ -0,0 +1,61 @@ +// Copyright © https://myCSharp.de - all rights reserved + +using Microsoft.Extensions.Primitives; +using Xunit; + +namespace MyCSharp.HttpClientHints.UnitTests; + +public class HttpClientHintsTests +{ + private static HttpClientHints Create(string? platform, string? platformVersion, string? architecture, string? model) + => new(null, platform, platformVersion, architecture, model, null, null, null, new Dictionary(StringComparer.Ordinal)); + + [Fact] + public void DecodedProperties_DecodeTheHeaderValues() + { + HttpClientHints hints = Create("\"Windows\"", "\"19.0.0\"", "\"x86\"", "\"Pixel \\\"9\\\"\""); + + Assert.Equal("\"Windows\"", hints.Platform); + Assert.Equal("Windows", hints.DecodedPlatform); + Assert.Equal("\"19.0.0\"", hints.PlatformVersion); + Assert.Equal("19.0.0", hints.DecodedPlatformVersion); + Assert.Equal("\"x86\"", hints.Architecture); + Assert.Equal("x86", hints.DecodedArchitecture); + Assert.Equal("\"Pixel \\\"9\\\"\"", hints.Model); + Assert.Equal("Pixel \"9\"", hints.DecodedModel); + } + + [Fact] + public void DecodedProperties_ReturnNull_WhenValuesAreMissingOrMalformed() + { + HttpClientHints hints = Create(null, "\"19.0.0", "\"x86\";bits=64", "\"Modèle\""); + + Assert.Null(hints.DecodedPlatform); + Assert.Null(hints.DecodedPlatformVersion); + Assert.Null(hints.DecodedArchitecture); + Assert.Null(hints.DecodedModel); + } + + [Fact] + public void DecodedProperties_FollowWithExpressions() + { + HttpClientHints hints = Create("\"Windows\"", null, null, null); + + HttpClientHints changed = hints with { Platform = "\"Linux\"" }; + + Assert.Equal("Windows", hints.DecodedPlatform); + Assert.Equal("Linux", changed.DecodedPlatform); + } + + [Fact] + public void Equality_DependsOnlyOnThePositionalValues() + { + HttpClientHints hints = Create("\"Windows\"", null, null, null); + HttpClientHints copy = hints with { }; + + _ = hints.DecodedPlatform; + + Assert.Equal(hints, copy); + Assert.Equal(hints.GetHashCode(), copy.GetHashCode()); + } +} diff --git a/version.json b/version.json index 5e0bc01..7832713 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": "4.0", + "version": "3.2", "nugetPackageVersion": { "semVer": 1 // optional. Set to either 1 or 2 to control how the NuGet package version string is generated. Default is 1. }, From 722d827af8c6838e1f9130584c7133b1e0a71349 Mon Sep 17 00:00:00 2001 From: BEN ABT Date: Sat, 21 Nov 2026 15:58:54 +0100 Subject: [PATCH 3/3] docs: explain snapshot and view, show decoded values in the sample - README: explain GetClientHints and GetClientHintsView, list the headers each option requests, and use Sec-CH-UA-Full-Version-List as the Additional example instead of Sec-CH-UA-Bitness, which Architecture already requests - README: show DecodeStructuredString for Sec-CH-UA-Bitness, show the install command for both packages, fix a typo - Sample: show header values next to their decoded values, decode Sec-CH-UA-Bitness, request Sec-CH-UA-Full-Version-List, and remove the empty template columns --- README.md | 45 ++++++++++++++++--- .../Program.cs | 2 +- .../Views/Home/Index.cshtml | 29 +++++++++--- 3 files changed, 61 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index fa8092a..bc08f6a 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,15 @@ Reading HTTP Client Hints with .NET ## NuGet -| NuGet | -|-| -| [![MyCSharp.HttpClientHints](https://img.shields.io/nuget/v/MyCSharp.HttpClientHints.svg?logo=nuget&label=MyCSharp.HttpClientHints)](https://www.nuget.org/packages/MyCSharp.HttpClientHints) | +| NuGet | Install | +|-|-| +| [![MyCSharp.HttpClientHints](https://img.shields.io/nuget/v/MyCSharp.HttpClientHints.svg?logo=nuget&label=MyCSharp.HttpClientHints)](https://www.nuget.org/packages/MyCSharp.HttpClientHints) | `dotnet add package MyCSharp.HttpClientHints` | | [![MyCSharp.HttpClientHints.AspNetCore](https://img.shields.io/nuget/v/MyCSharp.HttpClientHints.AspNetCore.svg?logo=nuget&label=MyCSharp.HttpClientHints.AspNetCore)](https://www.nuget.org/packages/MyCSharp.HttpClientHints.AspNetCore) | `dotnet add package MyCSharp.HttpClientHints.AspNetCore` | ## Client Hints -HTTP client hints are intended to completely replace the user agents (see [mycsharp/HttpUserAgentParser](https://github.com/mycsharp/HttpUserAgentParser)) of the browser in the long term and pay more attention to data protection. We are currently in a phase in which client hints are generally regarded as expiremental and therefore do not represent a complete alternative. +HTTP client hints are intended to completely replace the user agents (see [mycsharp/HttpUserAgentParser](https://github.com/mycsharp/HttpUserAgentParser)) of the browser in the long term and pay more attention to data protection. We are currently in a phase in which client hints are generally regarded as experimental and therefore do not represent a complete alternative. Furthermore, in contrast to the User-Agent header, not all client hints are provided automatically, but only on request after the first response from the client. @@ -55,6 +55,21 @@ using MyCSharp.HttpClientHints.AspNetCore; HttpClientHints clientHints = HttpClientHintsHttpContextExtensions.GetClientHints(httpContext); ``` +There are two ways to read the Client Hints of a request: + +| API | Returns | Behavior | +| --- | --- | --- | +| `httpContext.GetClientHints()` | `HttpClientHints` record | Reads the headers on the first call and returns the same instance for every further call during the request. | +| `httpContext.GetClientHintsView()` | `HttpClientHintsView` struct | Reads the current request headers on every property access. Creating the view and reading header values do not allocate. | + +`GetClientHints()` and `GetClientHintsView()` are also available on `IHeaderDictionary`. `GetClientHints()` on headers builds a new record on every call. + +```csharp +HttpClientHints clientHints = httpContext.GetClientHints(); +HttpClientHintsView view = httpContext.GetClientHintsView(); +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. ## Decoded values @@ -82,7 +97,17 @@ An absent header yields `null`. A quoted empty value such as `Sec-CH-UA-Model: " ## Customization -The `Additional` property can be used to define your own headers that are to be requested. +Each option requests these headers with `Accept-CH`: + +| Option | Requested headers | +| --- | --- | +| `UserAgent` | `User-Agent`, `Sec-CH-UA` | +| `Platform` | `Sec-CH-UA-Platform`, `Sec-CH-UA-Platform-Version` | +| `Architecture` | `Sec-CH-UA-Arch`, `Sec-CH-UA-Bitness` | +| `Device` | `Sec-CH-UA-Model` | +| `Mobile` | `Sec-CH-UA-Mobile` | + +The `Additional` property can be used to request further headers. For example, `FullVersionList` stays `null` unless you request `Sec-CH-UA-Full-Version-List`. ```csharp // Add Http Client Hint Options @@ -93,18 +118,24 @@ builder.Services.AddHttpClientHints(options => options.Architecture = true; options.Device = true; options.Mobile = true; - options.Additional = ["Sec-CH-UA-Bitness"]; + options.Additional = ["Sec-CH-UA-Full-Version-List"]; options.Lifetime = TimeSpan.FromDays(31); }); ``` -The `HttpClientHints` object has a reference to all headers received, making it very easy to read them out. Optionally, you can also inherit from the `HttpClientHints` class itself to simplify access. +The `HttpClientHints` object has a reference to all headers received, making it very easy to read them out. This includes headers without a property, such as `Sec-CH-UA-Bitness`. Optionally, you can also inherit from the `HttpClientHints` class itself to simplify access. ```csharp HttpClientHints clientHints = HttpClientHintsHttpContextExtensions.GetClientHints(httpContext); clientHints.Headers.TryGetValue("Sec-CH-UA-Bitness", out StringValues bitness); ``` +Like the platform, `Sec-CH-UA-Bitness` is sent as a quoted string such as `"64"`. `HttpClientHintsInterpreter.DecodeStructuredString` removes the quotes from any header value of this type. + +```csharp +string? decodedBitness = HttpClientHintsInterpreter.DecodeStructuredString(bitness); // 64 +``` + ## Build and test Use the .NET 11 SDK to build the solution. Both NuGet packages target .NET 8, 9, 10, and 11. The .NET 11 build uses `Microsoft.Extensions.Primitives` from the shared runtime. Install the corresponding runtimes to run the full test suite. diff --git a/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs b/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs index e0055fb..8a4bb82 100644 --- a/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs +++ b/samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs @@ -15,7 +15,7 @@ options.Architecture = true; options.Device = true; options.Mobile = true; - options.Additional = ["Sec-CH-UA-Bitness"]; + options.Additional = ["Sec-CH-UA-Full-Version-List"]; options.Lifetime = TimeSpan.FromDays(31); }); diff --git a/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml b/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml index 441af2a..ba3653d 100644 --- a/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml +++ b/samples/HttpClientHints.Samples.AspNetCoreMvc/Views/Home/Index.cshtml @@ -1,55 +1,70 @@ +@using Microsoft.Extensions.Primitives +@using MyCSharp.HttpClientHints +@using MyCSharp.HttpClientHints.AspNetCore @{ ViewData["Title"] = "Home Page"; - var httpContext = this.Context; - var clientHints = MyCSharp.HttpClientHints.AspNetCore.HttpClientHintsHttpContextExtensions.GetClientHints(httpContext.Request.Headers); + HttpClientHints clientHints = Context.GetClientHints(); + clientHints.Headers.TryGetValue("Sec-CH-UA-Bitness", out StringValues bitness); }

HTTP Client Hints

+

Browsers send most of these headers only after a response has requested them with Accept-CH. Reload the page if values are missing.

- - - + + + - + + + + + + + + + - + + + +
HeaderValueLastHandleValue as sentDecoded value
User-Agent @(clientHints.UserAgent)
Sec-CH-UA @(clientHints.UA)
Sec-CH-UA-Platform @(clientHints.Platform)@(clientHints.DecodedPlatform)
Sec-CH-UA-Platform-Version @(clientHints.PlatformVersion)@(clientHints.DecodedPlatformVersion)
Sec-CH-UA-Arch @(clientHints.Architecture)@(clientHints.DecodedArchitecture)
Sec-CH-UA-Bitness@(bitness)@(HttpClientHintsInterpreter.DecodeStructuredString(bitness))
Sec-CH-UA-Full-Version-List"Sec-CH-UA-Full-Version-List @(clientHints.FullVersionList)
Sec-CH-UA-Model @(clientHints.Model)@(clientHints.DecodedModel)
Sec-CH-UA-Mobile @(clientHints.Mobile)