How can I convert a stream to MemoryStream in Web Api Core? RRS feed

  • Question

  • User-1350042179 posted


    I would like to convert the value of HttpContext.Response.Body to a MemoryStream to save in a variable?

    This is my code:

       public async Task Invoke(HttpContext context)
                    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nLogTrace.config").GetCurrentClassLogger();
                    var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
                    await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
                    var requestBody = Encoding.UTF8.GetString(buffer);
                    context.Request.Body.Seek(0, SeekOrigin.Begin);
                    var originalBodyStream = context.Response.Body;
                    using (var responseBody = new MemoryStream())
                        context.Response.Body = responseBody;
                        await next(context);
                        context.Response.Body.Seek(0, SeekOrigin.Begin);
                        var response = await new StreamReader(context.Response.Body).ReadToEndAsync();
                        context.Response.Body.Seek(0, SeekOrigin.Begin);
                        "LLamada: " + (context.Request.Path.HasValue ? context.Request.Path.Value : string.Empty) +
                        " | Request: " + requestBody +
                        " | Response: " + response +
                        await responseBody.CopyToAsync(originalBodyStream);
                catch (Exception)

    I want to do this: 

    MemoryStream previousBody = context.Response.Body;


    context.Response.Body = responseBody;

    Since I catch the errors in catch statement
    Wednesday, March 18, 2020 2:44 PM

All replies

  • User475983607 posted

    Is the actual goal logging the request?  If so, see the following blog.


    Wednesday, March 18, 2020 2:54 PM
  • User283571144 posted

    Hi neoaguil17,


                       MemoryStream previousBody = context.Response.Body;

    As far as I know, stream is not as same as memorystream.

    The stream is the abstract base class and the memorystream, filestream,... is the examples of classes in the .NET framework that inherit from stream.

    The reason your codes throw the error is the context.Response.Body is not a memorysteam, its type is Microsoft.AspNetCore.Server.IIS.Core.WrappingStream.

    So you couldn't directly convert a stream to MemoryStream.

    The only way to doing get the steam to memory stream is using copyto method. We could copy WrappingStream to memory steam.

    Best Regards,


    Thursday, March 19, 2020 3:05 AM