liveBook · Manning

Memory stream

As explained in ASP.NET Core in Action, 3e

MemoryStream is a .NET stream implementation that stores readable and writable data in memory.

MemoryStream is a .NET stream implementation that keeps readable and writable data in memory. In middleware tests, it captures response content that would otherwise disappear into Stream.Null. section 36.1

Use a MemoryStream to inspect response content during an isolated middleware test:

  • Create the MemoryStream and assign it to DefaultHttpContext.Response.Body. section 36.1
  • Invoke the middleware, reposition the stream to its beginning, and read it with StreamReader. section 36.1
  • Assert that the captured string contains the expected response, such as "pong". section 36.1
Listing 36.3 Unit testing StatusMiddleware when a matching Path is provided
[Fact]
public async Task ReturnsPongBodyContent()
{
    var bodyStream = new MemoryStream();                           #1
    var context = new DefaultHttpContext();                        #1
    context.Response.Body = bodyStream;                            #1
    context.Request.Path = "/ping";                                #2
    RequestDelegate next = (ctx) => Task.CompletedTask;            #3
    var middleware = new StatusMiddleware(next: next);             #3
 
    await middleware.Invoke(context);                              #4
 
    string response;                                               #5
    bodyStream.Seek(0, SeekOrigin.Begin);                          #5
    using (var stringReader = new StreamReader(bodyStream))        #5
    {                                                              #5
        response = await stringReader.ReadToEndAsync();            #5
    }                                                              #5
 
    Assert.Equal("pong", response);                                #6
    Assert.Equal("text/plain", context.Response.ContentType);      #7
    Assert.Equal(200, context.Response.StatusCode);                #8
}

Shows a MemoryStream assigned to the response body before invoking middleware and reading the captured output. section 36.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains stream replacement, repositioning, and manual reading, without exploring stream internals.
Examples
Uses a /ping middleware test that captures and verifies a "pong" response body.
What it assumes
Assumes familiarity with C# streams and ASP.NET Core middleware tests.
What you can do after
Diagnose/debug with it by capturing middleware output and checking the resulting response content.
How it connects
Connects MemoryStream with DefaultHttpContext, Stream.Null, StreamReader, middleware, and unit testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.