-
Notifications
You must be signed in to change notification settings - Fork 10.4k
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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; | ||
|
||
/// <summary> | ||
/// Read JSON from the request and deserialize to the specified type. | ||
|
@@ -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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. 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(); | ||
} | ||
|
@@ -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(); | ||
} | ||
|
@@ -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(); | ||
} | ||
|
@@ -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(); | ||
} | ||
|
@@ -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(); | ||
} | ||
|
@@ -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)) | ||
|
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
@@ -3,7 +3,6 @@ | |||||||||
|
||||||||||
using System.Text; | ||||||||||
using System.Text.Json; | ||||||||||
using Microsoft.AspNetCore.Http; | ||||||||||
using Microsoft.Extensions.Logging; | ||||||||||
|
||||||||||
namespace Microsoft.AspNetCore.Mvc.Formatters; | ||||||||||
|
@@ -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"/>. | ||||||||||
|
@@ -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; | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||||||
} | ||||||||||
|
||||||||||
/// <summary> | ||||||||||
|
@@ -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) | ||||||||||
{ | ||||||||||
|
@@ -89,7 +109,7 @@ public sealed override async Task<InputFormatterResult> ReadRequestBodyAsync( | |||||||||
} | ||||||||||
finally | ||||||||||
{ | ||||||||||
if (usesTranscodingStream) | ||||||||||
if (inputStream is not null) | ||||||||||
{ | ||||||||||
await inputStream.DisposeAsync(); | ||||||||||
} | ||||||||||
|
@@ -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")] | ||||||||||
|
There was a problem hiding this comment.
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.
Copilot uses AI. Check for mistakes.