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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
85 changes: 72 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -55,11 +55,59 @@ 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

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.

| Request header | Property | Decoded property |
| --- | --- | --- |
| `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();
string? platformHeader = hints.Platform; // "Windows", including the two quote characters
bool isWindows = hints.DecodedPlatform == "Windows";
```

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.

## 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
Expand All @@ -70,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.
Expand All @@ -91,12 +145,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 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, 31,83 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
Expand All @@ -107,11 +165,12 @@ 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 | - | - |
| 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

Expand Down
36 changes: 36 additions & 0 deletions eng/Assert-CodeCoverage.ps1
Original file line number Diff line number Diff line change
@@ -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
}
8 changes: 8 additions & 0 deletions perf/HttpClientHints.Benchmarks/HttpClientHintBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ public int ReadViewProperties()
+ (view.Architecture?.Length ?? 0) + (view.Mobile == false ? 1 : 0);
}

[Benchmark]
public int ReadDecodedViewProperties()
{
HttpClientHintsView view = _headers.GetClientHintsView();
return (view.UA?.Length ?? 0) + (view.DecodedPlatform?.Length ?? 0)
+ (view.DecodedArchitecture?.Length ?? 0) + (view.Mobile == false ? 1 : 0);
}

[Benchmark]
public ClientHints GetClientHintsFromHeaders() => _headers.GetClientHints();

Expand Down
2 changes: 1 addition & 1 deletion samples/HttpClientHints.Samples.AspNetCoreMvc/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}

<div class="text-center">
<h1 class="display-4">HTTP Client Hints</h1>
<p>Browsers send most of these headers only after a response has requested them with <code>Accept-CH</code>. Reload the page if values are missing.</p>
<div>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Header</th>
<th scope="col">Value</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
<th scope="col">Value as sent</th>
<th scope="col">Decoded value</th>
</tr>
</thead>
<tbody>
<tr>
<td>User-Agent</td>
<td>@(clientHints.UserAgent)</td>
<td></td>
</tr>

<tr>
<td>Sec-CH-UA</td>
<td>@(clientHints.UA)</td>
<td></td>
</tr>
<tr>
<td>Sec-CH-UA-Platform</td>
<td>@(clientHints.Platform)</td>
<td>@(clientHints.DecodedPlatform)</td>
</tr>
<tr>
<td>Sec-CH-UA-Platform-Version</td>
<td>@(clientHints.PlatformVersion)</td>
<td>@(clientHints.DecodedPlatformVersion)</td>
</tr>
<tr>
<td>Sec-CH-UA-Arch</td>
<td>@(clientHints.Architecture)</td>
<td>@(clientHints.DecodedArchitecture)</td>
</tr>
<tr>
<td>Sec-CH-UA-Bitness</td>
<td>@(bitness)</td>
<td>@(HttpClientHintsInterpreter.DecodeStructuredString(bitness))</td>
</tr>
<tr>
<td>Sec-CH-UA-Full-Version-List"</td>
<td>Sec-CH-UA-Full-Version-List</td>
<td>@(clientHints.FullVersionList)</td>
<td></td>
</tr>
<tr>
<td>Sec-CH-UA-Model</td>
<td>@(clientHints.Model)</td>
<td>@(clientHints.DecodedModel)</td>
</tr>
<tr>
<td>Sec-CH-UA-Mobile</td>
<td>@(clientHints.Mobile)</td>
<td></td>
</tr>
</tbody>
</table>
Expand Down
Loading