3

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.

  • 1
    I wonder if might be something to do with the web server setting up that original `Body` stream and then not expecting it to be changed to something completely different when it comes time to write it out. Clearly, if that is true, it's not an obvious, observable issue that's being avoided as you don't see a problem, but it does seem like it could be something along the lines of the whole don't-replace-the-body-stream thing. – Kirk Larkin Jun 27 '19 at 13:49

0 Answers0