1
1
using System ;
2
+ using System . IO ;
2
3
using System . Threading . Tasks ;
4
+ using Microsoft . AspNetCore . Http ;
3
5
using Microsoft . AspNetCore . Mvc . Formatters ;
4
6
using Microsoft . Net . Http . Headers ;
5
7
using ProtoBuf . Meta ;
@@ -9,15 +11,15 @@ namespace WebApiContrib.Core.Formatter.Protobuf
9
11
public class ProtobufOutputFormatter : OutputFormatter
10
12
{
11
13
private readonly ProtobufFormatterOptions _options ;
12
-
13
- public ProtobufOutputFormatter ( ProtobufFormatterOptions protobufFormatterOptions )
14
- {
15
- ContentType = "application/x-protobuf" ;
16
- _options = protobufFormatterOptions ?? throw new ArgumentNullException ( nameof ( protobufFormatterOptions ) ) ;
17
- foreach ( var contentType in protobufFormatterOptions . SupportedContentTypes )
18
- {
19
- SupportedMediaTypes . Add ( new MediaTypeHeaderValue ( contentType ) ) ;
20
- }
14
+
15
+ public ProtobufOutputFormatter ( ProtobufFormatterOptions protobufFormatterOptions )
16
+ {
17
+ ContentType = "application/x-protobuf" ;
18
+ _options = protobufFormatterOptions ?? throw new ArgumentNullException ( nameof ( protobufFormatterOptions ) ) ;
19
+ foreach ( var contentType in protobufFormatterOptions . SupportedContentTypes )
20
+ {
21
+ SupportedMediaTypes . Add ( new MediaTypeHeaderValue ( contentType ) ) ;
22
+ }
21
23
}
22
24
23
25
private static Lazy < RuntimeTypeModel > model = new Lazy < RuntimeTypeModel > ( CreateTypeModel ) ;
@@ -36,12 +38,16 @@ private static RuntimeTypeModel CreateTypeModel()
36
38
return typeModel ;
37
39
}
38
40
39
- public override Task WriteResponseBodyAsync ( OutputFormatterWriteContext context )
41
+ public override async Task WriteResponseBodyAsync ( OutputFormatterWriteContext context )
40
42
{
41
43
var response = context . HttpContext . Response ;
42
-
43
- Model . Serialize ( response . Body , context . Object ) ;
44
- return Task . FromResult ( response ) ;
44
+
45
+ MemoryStream stream = new MemoryStream ( ) ;
46
+ Model . Serialize ( stream , context . Object ) ;
47
+
48
+ stream . Position = 0 ;
49
+ var sr = new StreamReader ( stream ) ;
50
+ await response . WriteAsync ( sr . ReadToEnd ( ) ) ;
45
51
}
46
52
}
47
53
}
0 commit comments