From 67b80ef8e7a680150f1833d01647f8f3f3de7c5d Mon Sep 17 00:00:00 2001 From: chenrui Date: Wed, 9 Oct 2019 12:26:09 +0800 Subject: [PATCH] fix AllowSynchronousIO of messagepack in core3.0 --- .../MessagePackInputFormatter.cs | 11 +++++++---- .../MessagePackOutputFormatter.cs | 9 ++++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackInputFormatter.cs b/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackInputFormatter.cs index eeb11f7..0b7112b 100644 --- a/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackInputFormatter.cs +++ b/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackInputFormatter.cs @@ -43,10 +43,13 @@ public override async Task ReadRequestBodyAsync(InputForma request.Body.Seek(0L, SeekOrigin.Begin); } - var result = MessagePackSerializer.NonGeneric.Deserialize(context.ModelType, request.Body, _options.FormatterResolver); - var formatterResult = await InputFormatterResult.SuccessAsync(result); - - return formatterResult; + using (MemoryStream stream = new MemoryStream()) + { + await request.Body.CopyToAsync(stream); + stream.Position = 0; + var result = MessagePackSerializer.NonGeneric.Deserialize(context.ModelType, stream, _options.FormatterResolver); + return await InputFormatterResult.SuccessAsync(result); + } } protected override bool CanReadType(Type type) diff --git a/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackOutputFormatter.cs b/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackOutputFormatter.cs index 7679306..ff0bca8 100644 --- a/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackOutputFormatter.cs +++ b/src/WebApiContrib.Core.Formatter.MessagePack/MessagePackOutputFormatter.cs @@ -24,15 +24,18 @@ public MessagePackOutputFormatter(MessagePackFormatterOptions messagePackFormatt } } - public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) + public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } - MessagePackSerializer.NonGeneric.Serialize(context.ObjectType, context.HttpContext.Response.Body, context.Object, _options.FormatterResolver); - return Task.FromResult(0); + using (MemoryStream stream = new MemoryStream()) + { + MessagePackSerializer.NonGeneric.Serialize(context.ObjectType, stream, context.Object, _options.FormatterResolver); + await context.HttpContext.Response.Body.WriteAsync(stream.ToArray(), 0, (int)stream.Length); + } } } }