Skip to content

Use Encoding.CreateTranscodingStream #21509

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 2 commits into from
May 6, 2020
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
14 changes: 7 additions & 7 deletions src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters.Json;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Mvc.Formatters
Expand Down Expand Up @@ -67,7 +66,7 @@ public sealed override async Task<InputFormatterResult> ReadRequestBodyAsync(
}

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

object model;
try
Expand Down Expand Up @@ -98,9 +97,9 @@ public sealed override async Task<InputFormatterResult> ReadRequestBodyAsync(
}
finally
{
if (inputStream is TranscodingReadStream transcoding)
if (usesTranscodingStream)
{
await transcoding.DisposeAsync();
await inputStream.DisposeAsync();
}
}

Expand All @@ -119,14 +118,15 @@ public sealed override async Task<InputFormatterResult> ReadRequestBodyAsync(
}
}

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

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

private static class Log
Expand Down
71 changes: 37 additions & 34 deletions src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,11 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters.Json;

namespace Microsoft.AspNetCore.Mvc.Formatters
{
Expand Down Expand Up @@ -73,44 +70,50 @@ public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteCon

var httpContext = context.HttpContext;

var writeStream = GetWriteStream(httpContext, selectedEncoding);
try
// context.ObjectType reflects the declared model type when specified.
// For polymorphic scenarios where the user declares a return type, but returns a derived type,
// we want to serialize all the properties on the derived type. This keeps parity with
// the behavior you get when the user does not declare the return type and with Json.Net at least at the top level.
var objectType = context.Object?.GetType() ?? context.ObjectType ?? typeof(object);

var responseStream = httpContext.Response.Body;
if (selectedEncoding.CodePage == Encoding.UTF8.CodePage)
{
await JsonSerializer.SerializeAsync(responseStream, context.Object, objectType, SerializerOptions);
await responseStream.FlushAsync();
}
else
{
// context.ObjectType reflects the declared model type when specified.
// For polymorphic scenarios where the user declares a return type, but returns a derived type,
// we want to serialize all the properties on the derived type. This keeps parity with
// the behavior you get when the user does not declare the return type and with Json.Net at least at the top level.
var objectType = context.Object?.GetType() ?? context.ObjectType ?? typeof(object);
await JsonSerializer.SerializeAsync(writeStream, context.Object, objectType, SerializerOptions);
// JsonSerializer only emits UTF8 encoded output, but we need to write the response in the encoding specified by
// selectedEncoding
var transcodingStream = Encoding.CreateTranscodingStream(httpContext.Response.Body, selectedEncoding, Encoding.UTF8, leaveOpen: true);

// The transcoding streams use Encoders and Decoders that have internal buffers. We need to flush these
// when there is no more data to be written. Stream.FlushAsync isn't suitable since it's
// acceptable to Flush a Stream (multiple times) prior to completion.
if (writeStream is TranscodingWriteStream transcodingStream)
ExceptionDispatchInfo exceptionDispatchInfo = null;
try
{
await transcodingStream.FinalWriteAsync(CancellationToken.None);
await JsonSerializer.SerializeAsync(transcodingStream, context.Object, objectType, SerializerOptions);
await transcodingStream.FlushAsync();
}
await writeStream.FlushAsync();
}
finally
{
if (writeStream is TranscodingWriteStream transcodingStream)
catch (Exception ex)
{
await transcodingStream.DisposeAsync();
// TranscodingStream may write to the inner stream as part of it's disposal.
// We do not want this exception "ex" to be eclipsed by any exception encountered during the write. We will stash it and
// explicitly rethrow it during the finally block.
exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex);
}
}
}
finally
{
try
{
await transcodingStream.DisposeAsync();
}
catch when (exceptionDispatchInfo != null)
{
}

private Stream GetWriteStream(HttpContext httpContext, Encoding selectedEncoding)
{
if (selectedEncoding.CodePage == Encoding.UTF8.CodePage)
{
// JsonSerializer does not write a BOM. Therefore we do not have to handle it
// in any special way.
return httpContext.Response.Body;
exceptionDispatchInfo?.Throw();
}
}

return new TranscodingWriteStream(httpContext.Response.Body, selectedEncoding);
}
}
}
223 changes: 0 additions & 223 deletions src/Mvc/Mvc.Core/src/Formatters/TranscodingReadStream.cs

This file was deleted.

Loading