Search code examples
c#asp.net-corememorystream

Why MemoryStream() has data even though it is not initialized with any source of data


I have a test .Net Core application and I want to read http responses from pipeline for my personal practice.

This minimum code example provides http response. I know it is destroying the response body which I need to fix it latter, but it is not my question. My question is how does MemoryStream() has http response inside it even though I didn't initialized it with any source of data?

"Startup.cs":

public void Configure(IApplicationBuilder app)
{
    app.Use(async (context, next) =>
    {
        using (var swapStream = new MemoryStream())
        {
            context.Response.Body = swapStream;

            await next.Invoke();

            swapStream.Seek(0, SeekOrigin.Begin);
            string responseBody = new StreamReader(swapStream).ReadToEnd();
        }
    });
 }

As you can see MemoryStream() is not initialized with any source of data at all. But in the end in responseBody I can see my http response. What makes me more confused is that if I remove context.Response.Body = swapStream; then I don't have http response in responseBody.

It would be appreciated if someone could help me to understand how does this code works.


Solution

  • Something else is writing to the stream, it happens when you call

    await next.Invoke();
    

    You are replacing the response stream with your memorystream, and something later in the chain writes to that stream.