6
6
using System . Text ;
7
7
using System . Text . Encodings . Web ;
8
8
using System . Text . Json ;
9
- using System . Threading ;
10
9
using System . Threading . Tasks ;
11
10
using Microsoft . AspNetCore . Http ;
12
- using Microsoft . AspNetCore . Mvc . Formatters . Json ;
13
11
14
12
namespace Microsoft . AspNetCore . Mvc . Formatters
15
13
{
@@ -73,7 +71,8 @@ public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteCon
73
71
74
72
var httpContext = context . HttpContext ;
75
73
76
- var writeStream = GetWriteStream ( httpContext , selectedEncoding ) ;
74
+ var ( writeStream , usesTranscodingStream ) = GetWriteStream ( httpContext , selectedEncoding ) ;
75
+
77
76
try
78
77
{
79
78
// context.ObjectType reflects the declared model type when specified.
@@ -82,35 +81,29 @@ public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteCon
82
81
// the behavior you get when the user does not declare the return type and with Json.Net at least at the top level.
83
82
var objectType = context . Object ? . GetType ( ) ?? context . ObjectType ?? typeof ( object ) ;
84
83
await JsonSerializer . SerializeAsync ( writeStream , context . Object , objectType , SerializerOptions ) ;
85
-
86
- // The transcoding streams use Encoders and Decoders that have internal buffers. We need to flush these
87
- // when there is no more data to be written. Stream.FlushAsync isn't suitable since it's
88
- // acceptable to Flush a Stream (multiple times) prior to completion.
89
- if ( writeStream is TranscodingWriteStream transcodingStream )
90
- {
91
- await transcodingStream . FinalWriteAsync ( CancellationToken . None ) ;
92
- }
93
84
await writeStream . FlushAsync ( ) ;
94
85
}
95
86
finally
96
87
{
97
- if ( writeStream is TranscodingWriteStream transcodingStream )
88
+ if ( usesTranscodingStream )
98
89
{
99
- await transcodingStream . DisposeAsync ( ) ;
90
+ await writeStream . DisposeAsync ( ) ;
100
91
}
101
92
}
93
+
102
94
}
103
95
104
- private Stream GetWriteStream ( HttpContext httpContext , Encoding selectedEncoding )
96
+ private ( Stream writeStream , bool usesTranscodingStream ) GetWriteStream ( HttpContext httpContext , Encoding selectedEncoding )
105
97
{
106
98
if ( selectedEncoding . CodePage == Encoding . UTF8 . CodePage )
107
99
{
108
100
// JsonSerializer does not write a BOM. Therefore we do not have to handle it
109
101
// in any special way.
110
- return httpContext . Response . Body ;
102
+ return ( httpContext . Response . Body , false ) ;
111
103
}
112
104
113
- return new TranscodingWriteStream ( httpContext . Response . Body , selectedEncoding ) ;
105
+ var writeStream = Encoding . CreateTranscodingStream ( httpContext . Response . Body , selectedEncoding , Encoding . UTF8 , leaveOpen : true ) ;
106
+ return ( writeStream , true ) ;
114
107
}
115
108
}
116
109
}
0 commit comments