Skip to content

Use PipeReader JsonSerializer overloads #62895

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 25, 2025
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
135 changes: 109 additions & 26 deletions src/Http/Http.Extensions/src/HttpRequestJsonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ public static class HttpRequestJsonExtensions
"Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.";
private const string RequiresDynamicCodeMessage = "JSON serialization and deserialization might require types that cannot be statically analyzed and need runtime code generation. " +
"Use the overload that takes a JsonTypeInfo or JsonSerializerContext for native AOT applications.";
// Fallback to the stream-based overloads for JsonSerializer.DeserializeAsync
// This is to give users with custom JsonConverter implementations the chance to update their
// converters to support ReadOnlySequence<T> if needed while still keeping their apps working.
private static readonly bool _useStreamJsonOverload = AppContext.TryGetSwitch("Microsoft.AspNetCore.UseStreamBasedJsonParsing", out var isEnabled) && isEnabled;
Copy link
Preview

Copilot AI Jul 24, 2025

Choose a reason for hiding this comment

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

The same AppContext switch name issue exists here. Both classes use the same switch name but it should be consistent and clearly indicate its purpose of choosing between Stream and PipeReader overloads.

Suggested change
private static readonly bool _useStreamJsonOverload = AppContext.TryGetSwitch("Microsoft.AspNetCore.UseStreamBasedJsonParsing", out var isEnabled) && isEnabled;
private static readonly bool _useStreamJsonOverload = AppContext.TryGetSwitch("Microsoft.AspNetCore.Json.UseStreamOverPipeReader", out var isEnabled) && isEnabled;

Copilot uses AI. Check for mistakes.


/// <summary>
/// Read JSON from the request and deserialize to the specified type.
Expand Down Expand Up @@ -68,15 +72,33 @@ public static class HttpRequestJsonExtensions
options ??= ResolveSerializerOptions(request.HttpContext);

var encoding = GetEncodingFromCharset(charset);
var (inputStream, usesTranscodingStream) = GetInputStream(request.HttpContext, encoding);
Stream? inputStream = null;
ValueTask<TValue?> deserializeTask;

try
{
return await JsonSerializer.DeserializeAsync<TValue>(inputStream, options, cancellationToken);
if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage)
Copy link
Member

Choose a reason for hiding this comment

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

Nit: Is there anyway for us to dedupe this logic across the different extension methods? Maybe a helper that figures out what serialization invocation to use based on the context switch and return the associated task?

Copy link
Member Author

Choose a reason for hiding this comment

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

The difficulty here is that each of the HttpRequestJsonExtension methods use a different overload of DeserializeAsync.
We could in theory share the other checks, but I'm not sure it's much cleaner:

public static async ValueTask<object?> ReadFromJsonAsync(
    this HttpRequest request,
    Type type,
    JsonSerializerContext context,
    CancellationToken cancellationToken = default)
{
    Stream? inputStream = null;
    bool isTranscodedStream = false;
    ValueTask<object?> deserializeTask;

    try
    {
        (var pipeReader, inputStream, isTranscodedStream) = Shared(request);
        if (pipeReader is not null)
        {
            deserializeTask = JsonSerializer.DeserializeAsync(pipeReader, type, context, cancellationToken);
        }
        else
        {
            deserializeTask = JsonSerializer.DeserializeAsync(inputStream, type, context, cancellationToken);
        }

        return await deserializeTask;
    }
    finally
    {
        if (isTranscodedStream)
        {
            await inputStream!.DisposeAsync();
        }
    }
}

private static (PipeReader?, Stream?, bool) Shared(HttpRequest request)
{
    if (!request.HasJsonContentType(out var charset))
    {
        ThrowContentTypeError(request);
    }

    var encoding = GetEncodingFromCharset(charset);

    if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage)
    {
        if (_useStreamJsonOverload)
        {
            return (null, request.Body, false);
        }
        return (request.BodyReader, null, false);
    }

    var inputStream = Encoding.CreateTranscodingStream(request.Body, encoding, Encoding.UTF8, leaveOpen: true);
    return (null, inputStream, true);
}

{
if (_useStreamJsonOverload)
{
deserializeTask = JsonSerializer.DeserializeAsync<TValue>(request.Body, options, cancellationToken);
}
else
{
deserializeTask = JsonSerializer.DeserializeAsync<TValue>(request.BodyReader, options, cancellationToken);
}
}
else
{
inputStream = Encoding.CreateTranscodingStream(request.Body, encoding, Encoding.UTF8, leaveOpen: true);
deserializeTask = JsonSerializer.DeserializeAsync<TValue>(inputStream, options, cancellationToken);
}

return await deserializeTask;
}
finally
{
if (usesTranscodingStream)
if (inputStream is not null)
{
await inputStream.DisposeAsync();
}
Expand Down Expand Up @@ -106,15 +128,33 @@ public static class HttpRequestJsonExtensions
}

var encoding = GetEncodingFromCharset(charset);
var (inputStream, usesTranscodingStream) = GetInputStream(request.HttpContext, encoding);
Stream? inputStream = null;
ValueTask<TValue?> deserializeTask;

try
{
return await JsonSerializer.DeserializeAsync(inputStream, jsonTypeInfo, cancellationToken);
if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage)
{
if (_useStreamJsonOverload)
{
deserializeTask = JsonSerializer.DeserializeAsync(request.Body, jsonTypeInfo, cancellationToken);
}
else
{
deserializeTask = JsonSerializer.DeserializeAsync(request.BodyReader, jsonTypeInfo, cancellationToken);
}
}
else
{
inputStream = Encoding.CreateTranscodingStream(request.Body, encoding, Encoding.UTF8, leaveOpen: true);
deserializeTask = JsonSerializer.DeserializeAsync(inputStream, jsonTypeInfo, cancellationToken);
}

return await deserializeTask;
}
finally
{
if (usesTranscodingStream)
if (inputStream is not null)
{
await inputStream.DisposeAsync();
}
Expand Down Expand Up @@ -144,15 +184,33 @@ public static class HttpRequestJsonExtensions
}

var encoding = GetEncodingFromCharset(charset);
var (inputStream, usesTranscodingStream) = GetInputStream(request.HttpContext, encoding);
Stream? inputStream = null;
ValueTask<object?> deserializeTask;

try
{
return await JsonSerializer.DeserializeAsync(inputStream, jsonTypeInfo, cancellationToken);
if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage)
{
if (_useStreamJsonOverload)
{
deserializeTask = JsonSerializer.DeserializeAsync(request.Body, jsonTypeInfo, cancellationToken);
}
else
{
deserializeTask = JsonSerializer.DeserializeAsync(request.BodyReader, jsonTypeInfo, cancellationToken);
}
}
else
{
inputStream = Encoding.CreateTranscodingStream(request.Body, encoding, Encoding.UTF8, leaveOpen: true);
deserializeTask = JsonSerializer.DeserializeAsync(inputStream, jsonTypeInfo, cancellationToken);
}

return await deserializeTask;
}
finally
{
if (usesTranscodingStream)
if (inputStream is not null)
{
await inputStream.DisposeAsync();
}
Expand Down Expand Up @@ -206,15 +264,33 @@ public static class HttpRequestJsonExtensions
options ??= ResolveSerializerOptions(request.HttpContext);

var encoding = GetEncodingFromCharset(charset);
var (inputStream, usesTranscodingStream) = GetInputStream(request.HttpContext, encoding);
Stream? inputStream = null;
ValueTask<object?> deserializeTask;

try
{
return await JsonSerializer.DeserializeAsync(inputStream, type, options, cancellationToken);
if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage)
{
if (_useStreamJsonOverload)
{
deserializeTask = JsonSerializer.DeserializeAsync(request.Body, type, options, cancellationToken);
}
else
{
deserializeTask = JsonSerializer.DeserializeAsync(request.BodyReader, type, options, cancellationToken);
}
}
else
{
inputStream = Encoding.CreateTranscodingStream(request.Body, encoding, Encoding.UTF8, leaveOpen: true);
deserializeTask = JsonSerializer.DeserializeAsync(inputStream, type, options, cancellationToken);
}

return await deserializeTask;
}
finally
{
if (usesTranscodingStream)
if (inputStream is not null)
{
await inputStream.DisposeAsync();
}
Expand Down Expand Up @@ -248,15 +324,33 @@ public static class HttpRequestJsonExtensions
}

var encoding = GetEncodingFromCharset(charset);
var (inputStream, usesTranscodingStream) = GetInputStream(request.HttpContext, encoding);
Stream? inputStream = null;
ValueTask<object?> deserializeTask;

try
{
return await JsonSerializer.DeserializeAsync(inputStream, type, context, cancellationToken);
if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage)
{
if (_useStreamJsonOverload)
{
deserializeTask = JsonSerializer.DeserializeAsync(request.Body, type, context, cancellationToken);
}
else
{
deserializeTask = JsonSerializer.DeserializeAsync(request.BodyReader, type, context, cancellationToken);
}
}
else
{
inputStream = Encoding.CreateTranscodingStream(request.Body, encoding, Encoding.UTF8, leaveOpen: true);
deserializeTask = JsonSerializer.DeserializeAsync(inputStream, type, context, cancellationToken);
}

return await deserializeTask;
}
finally
{
if (usesTranscodingStream)
if (inputStream is not null)
{
await inputStream.DisposeAsync();
}
Expand Down Expand Up @@ -312,17 +406,6 @@ private static void ThrowContentTypeError(HttpRequest request)
throw new InvalidOperationException($"Unable to read the request as JSON because the request content type '{request.ContentType}' is not a known JSON content type.");
}

private static (Stream inputStream, bool usesTranscodingStream) GetInputStream(HttpContext httpContext, Encoding? encoding)
{
if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage)
{
return (httpContext.Request.Body, false);
}

var inputStream = Encoding.CreateTranscodingStream(httpContext.Request.Body, encoding, Encoding.UTF8, leaveOpen: true);
return (inputStream, true);
}

private static Encoding? GetEncodingFromCharset(StringSegment charset)
{
if (charset.Equals("utf-8", StringComparison.OrdinalIgnoreCase))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public async Task ReadFromJsonAsyncGeneric_WithCancellationToken_CancellationRai
cts.Cancel();

// Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () => await readTask);
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await readTask);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ public async Task BindAsyncWithBodyArgument()
Assert.Equal("Write more tests!", todo!.Name);
}

[Fact]
[Fact(Skip = "Resetting Stream.Position to 0 doesn't work with StreamPipeReader currently.")]
public async Task BindAsyncRunsBeforeBodyBinding()
{
Todo originalTodo = new()
Expand Down
39 changes: 24 additions & 15 deletions src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Mvc.Formatters;
Expand All @@ -15,6 +14,7 @@ public partial class SystemTextJsonInputFormatter : TextInputFormatter, IInputFo
{
private readonly JsonOptions _jsonOptions;
private readonly ILogger<SystemTextJsonInputFormatter> _logger;
private readonly bool _useStreamJsonOverload;

/// <summary>
/// Initializes a new instance of <see cref="SystemTextJsonInputFormatter"/>.
Expand All @@ -35,6 +35,11 @@ public SystemTextJsonInputFormatter(
SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson);
SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson);
SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax);

// Fallback to the stream-based overloads for JsonSerializer.DeserializeAsync
// This is to give users with custom JsonConverter implementations the chance to update their
// converters to support ReadOnlySequence<T> if needed while still keeping their apps working.
_useStreamJsonOverload = AppContext.TryGetSwitch("Microsoft.AspNetCore.UseStreamBasedJsonParsing", out var isEnabled) && isEnabled;
Copy link
Preview

Copilot AI Jul 24, 2025

Choose a reason for hiding this comment

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

The AppContext switch name contains a typo or inconsistency. The switch is named 'UseStreamBasedJsonParsing' but the behavior is actually controlling whether to use Stream vs PipeReader overloads. Consider renaming to 'Microsoft.AspNetCore.Json.UseStreamOverloads' for clarity.

Suggested change
_useStreamJsonOverload = AppContext.TryGetSwitch("Microsoft.AspNetCore.UseStreamBasedJsonParsing", out var isEnabled) && isEnabled;
_useStreamJsonOverload =
(AppContext.TryGetSwitch("Microsoft.AspNetCore.Json.UseStreamOverloads", out var isNewEnabled) && isNewEnabled) ||
(AppContext.TryGetSwitch("Microsoft.AspNetCore.UseStreamBasedJsonParsing", out var isOldEnabled) && isOldEnabled);

Copilot uses AI. Check for mistakes.

}

/// <summary>
Expand All @@ -58,12 +63,27 @@ public sealed override async Task<InputFormatterResult> ReadRequestBodyAsync(
ArgumentNullException.ThrowIfNull(encoding);

var httpContext = context.HttpContext;
var (inputStream, usesTranscodingStream) = GetInputStream(httpContext, encoding);

object? model;
Stream? inputStream = null;
try
{
model = await JsonSerializer.DeserializeAsync(inputStream, context.ModelType, SerializerOptions);
if (encoding.CodePage == Encoding.UTF8.CodePage)
{
if (_useStreamJsonOverload)
{
model = await JsonSerializer.DeserializeAsync(httpContext.Request.Body, context.ModelType, SerializerOptions);
}
else
{
model = await JsonSerializer.DeserializeAsync(httpContext.Request.BodyReader, context.ModelType, SerializerOptions);
}
}
else
{
inputStream = Encoding.CreateTranscodingStream(httpContext.Request.Body, encoding, Encoding.UTF8, leaveOpen: true);
model = await JsonSerializer.DeserializeAsync(inputStream, context.ModelType, SerializerOptions);
}
}
catch (JsonException jsonException)
{
Expand All @@ -89,7 +109,7 @@ public sealed override async Task<InputFormatterResult> ReadRequestBodyAsync(
}
finally
{
if (usesTranscodingStream)
if (inputStream is not null)
{
await inputStream.DisposeAsync();
}
Expand Down Expand Up @@ -123,17 +143,6 @@ private Exception WrapExceptionForModelState(JsonException jsonException)
return new InputFormatterException(jsonException.Message, jsonException);
}

private static (Stream inputStream, bool usesTranscodingStream) GetInputStream(HttpContext httpContext, Encoding encoding)
{
if (encoding.CodePage == Encoding.UTF8.CodePage)
{
return (httpContext.Request.Body, false);
}

var inputStream = Encoding.CreateTranscodingStream(httpContext.Request.Body, encoding, Encoding.UTF8, leaveOpen: true);
return (inputStream, true);
}

private static partial class Log
{
[LoggerMessage(1, LogLevel.Debug, "JSON input formatter threw an exception: {Message}", EventName = "SystemTextJsonInputException")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
<argument>ILLink</argument>
<argument>IL2026</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.&lt;ReadRequestBodyAsync&gt;d__8.MoveNext</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.&lt;ReadRequestBodyAsync&gt;d__9.MoveNext</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
Expand Down
Loading