Why original body is set back in Asp.Net Core compression middleware?

Viewed 91

In many code snippets that include modification of request or response body in Asp.Net, the body stream just replaced with new and the next step called. For example, here: https://stackoverflow.com/a/44500627 And here: Request content decompression in ASP.Net Core

However, in source of Asp.Net Core itself after handling request, old original body of response are returned back to the response object. See here: https://github.com/aspnet/BasicMiddleware/blob/master/src/Microsoft.AspNetCore.ResponseCompression/ResponseCompressionMiddleware.cs

Are there any reason to put original stream back into response object in second case?

I will show key difference:

Without returning original stream

public Task Invoke(HttpContext context)
{
    if(NeedCompress(context))
    { 
        Stream oldBody = context.Response.Body;
        context.Response.Body = new GZipStream(oldBody, CompressionMode.Fastest, leaveOpen:true);
    }
    return next(context);
}

With returning old body:

public Task Invoke(HttpContext context)
{
    if(NeedCompress(context))
    { 
        Stream oldBody = context.Response.Body;
        Stream newBody = new GZipStream(oldBody, CompressionMode.Fastest, leaveOpen:true);
        context.Response.Body = newBody;
        await next(context);
        newBody.Dispose()
        context.Response.Body = oldBody; // Why?
    }
    else
        await next(context);
}

In my code I used first approach and it like to work. However I am uncertain that it is correct.

0 Answers
Related