ASP.NET Core压缩中间件-空响应

问题描述:

我正在使用此存储库中的一些自定义压缩中间件(粘贴在下面).根据第一个请求,内容将被压缩.对于此后的每个请求,响应都将返回为完全空(Content-Length为0).

I am using some custom compression middleware from this repository (pasted below). Upon the first request, the content is compressed just fine. For every request after that, the response comes back as completely empty (with a Content-Length of 0).

这只有在从ASP.NET Core RC2迁移到RTM之后才开始发生.

This only started happening after migrating from ASP.NET Core RC2 to RTM.

有人知道为什么会这样吗?

Does anyone know why this is happening?

CompressionMiddleware:

public class CompressionMiddleware
{
    private readonly RequestDelegate _next;

    public CompressionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (IsGZipSupported(context))
        {
            string acceptEncoding = context.Request.Headers["Accept-Encoding"];

            var buffer = new MemoryStream();
            var stream = context.Response.Body;
            context.Response.Body = buffer;
            await _next(context);

            if (acceptEncoding.Contains("gzip"))
            {
                var gstream = new GZipStream(stream, CompressionLevel.Optimal);
                context.Response.Headers.Add("Content-Encoding", new[] { "gzip" });
                buffer.Seek(0, SeekOrigin.Begin);
                await buffer.CopyToAsync(gstream);
                gstream.Dispose();
            }
            else
            {
                var gstream = new DeflateStream(stream, CompressionLevel.Optimal);
                context.Response.Headers.Add("Content-Encoding", new[] { "deflate" });
                buffer.Seek(0, SeekOrigin.Begin);
                await buffer.CopyToAsync(gstream);
                gstream.Dispose();
            }
        }
        else
        {
            await _next(context);
        }
    }

    public bool IsGZipSupported(HttpContext context)
    {
        string acceptEncoding = context.Request.Headers["Accept-Encoding"];
        return !string.IsNullOrEmpty(acceptEncoding) &&
               (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate"));
    }
}