Skip to content

Skip MediaTypeHeaderValue parsing for common JSON request content types - #70196

Closed
davidfowl wants to merge 3 commits into
mainfrom
perf/http-json-content-type
Closed

davidfowl wants to merge 3 commits into
mainfrom
perf/http-json-content-type

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

HttpRequestJsonExtensions.HasJsonContentType calls MediaTypeHeaderValue.TryParse on every call. That allocates a MediaTypeHeaderValue, plus a parameter list and NameValueHeaderValue when a charset is present. For a minimal API endpoint with a JSON body it runs twice per request: once in the RequestDelegateFactory 415 check and again inside ReadFromJsonAsync.

This change checks for the two overwhelmingly common values first, using an ordinal-ignore-case compare:

  • application/json
  • application/json; charset=utf-8 (what HttpClient's JsonContent sends)

These exact strings always parse to the JSON media type, with no charset in the first case and utf-8 in the second. The fast path returns the same result and an equivalent charset (GetEncodingFromCharset compares case-insensitively). Every other value, including +json suffixes, other charsets, extra parameters and odd whitespace, goes through the existing parser unchanged.

Benchmark

BenchmarkDotNet InProcess, HttpRequestJsonContentTypeBenchmarks (added). Three interleaved rounds:

Method main PR main alloc PR alloc
HasJsonContentType application/json 83.8 / 92.4 / 97.4 ns 16.2 / 15.6 / 16.4 ns 48 B 0 B
HasJsonContentType application/json; charset=utf-8 175.6 / 184.7 / 220.5 ns 22.3 / 21.8 / 22.8 ns 224 B 0 B
HasJsonContentType application/problem+json (not fast-pathed) 106.4 / 111.0 / 108.2 ns 118.9 / 126.3 / 118.6 ns 48 B 48 B
ReadFromJsonAsync (fresh DefaultHttpContext + small object, charset=utf-8) 1.863 / 1.593 / 1.578 us 1.359 / 1.340 / 1.424 us 2,376 B 2,152 B

Content types that miss the fast path pay about 10 ns for the two failed compares.

Tests

Added cases to the HasJsonContentType theory: no-space charset, utf-16, extra parameters, application/jsonx and an unknown charset. Added a ReadFromJsonAsync theory over casing and spacing variants of the fast-path values. All of these pass on both main and this branch. All 2304 Http.Extensions tests pass.

HasJsonContentType runs for every minimal API JSON body (once in the
RequestDelegateFactory check and again in ReadFromJsonAsync) and
allocated a MediaTypeHeaderValue each time. Match "application/json"
and "application/json; charset=utf-8" ordinal-ignore-case first; these
parse to the same media type and charset, so results are unchanged.
Everything else uses the existing parser.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 16:38
@github-actions github-actions Bot added the area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions label Oct 31, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The benchmark rewinds the stream but leaves the cached BodyReader exhausted, causing subsequent invocations to throw JsonException instead of measuring successful deserialization.

1 open issue
What changed in this PR

This PR reduces parsing allocations in HTTP request JSON handling by fast-pathing two common content types while retaining the existing parser for other values.

Changes:

  • Adds case-insensitive checks for application/json and application/json; charset=utf-8.
  • Extends tests for casing, spacing, charset, and fallback behavior.
  • Adds benchmarks for content-type checks and JSON deserialization.
File Description
src/​Http/​Http/​perf/​Microbenchmarks/​HttpRequestJsonContentTypeBenchmarks.cs Adds content-type and deserialization benchmarks.
src/​Http/​Http.Extensions/​test/​HttpRequestJsonExtensionsTests.cs Expands content-type recognition and UTF-8 deserialization coverage.
src/​Http/​Http.Extensions/​src/​HttpRequestJsonExtensions.cs Bypasses media-type parsing for two common JSON content types.

Review effort: Balanced

Copy link
Copy Markdown
Member Author

Heads-up for reviewers: this PR overlaps with #70119, which was opened earlier from the same account and adds an allocation-free fast path to the same private HasJsonContentType. #70119 is more general: it handles any application/json; charset=<token>. This PR only matches the two most common exact strings. They are not meant to be merged together. #70119 covers this case, so this PR can be closed in its favor. The benchmark (HttpRequestJsonContentTypeBenchmarks) and test rows here can be ported if useful.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit (556eb2f). The previous run failed only the Blazor E2E test ServerRoutingTest.NavigationLock_CanBlockExternalNavigation (Build Analysis reports a 27.24% failure rate), a Selenium navigation assertion in Components unrelated to this Http change.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Copy link
Copy Markdown
Member Author

CI update: aspnetcore-ci passed. Only aspnetcore-components-e2e failed, on Blazor Selenium tests unrelated to this JSON content-type change:

  • VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements
  • BlazorWebJsInitializersTest.InitializersRunsModernCallbacksByDefaultWhenPresent
  • RedirectionTest.NavigationException_InAsyncContext_DoesNotBecomeUnobservedTaskException

That pipeline is failing on main in 4 of the last 5 commits, so I'm not pushing another empty commit (it was already retriggered once).

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Copy link
Copy Markdown
Member Author

Superseded by #70119

The owner is keeping the earlier PR #70119, which covers the same change. Closing this duplicate is left to the maintainers. I will not push or retrigger anything further on this PR.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants