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

  • Question

  • User-1350042179 posted

    Hi

    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)
            {
                try
                {
                    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nLogTrace.config").GetCurrentClassLogger();
                    context.Request.EnableBuffering();
    
                    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);
    
                        logger.Info(
                        "LLamada: " + (context.Request.Path.HasValue ? context.Request.Path.Value : string.Empty) +
                        " | Request: " + requestBody +
                        " | Response: " + response +
                        Environment.NewLine);
                        await responseBody.CopyToAsync(originalBodyStream);
                    }
                }
                catch (Exception)
                {
    
                }
            }

    I want to do this: 

    MemoryStream previousBody = context.Response.Body;

    Before

    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.

    https://exceptionnotfound.net/using-middleware-to-log-requests-and-responses-in-asp-net-core/

    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,

    Brando

    Thursday, March 19, 2020 3:05 AM