ASP.NET Core Compression Middleware - Empty Reponse

此生再无相见时 提交于 2019-12-12 01:47:31

问题


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).

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"));
    }
}

回答1:


I have found the following in "Add HTTP compression middleware" issue:

I have added gzip and it worked, but first request. I mean in the first request, the response page is null (context.Response.Body) but when you refresh the page (just once) it works correctly after that.(I don't know why but I have to solve it)

And response on question is:

You need to update context.Response.Headers["Content-Length"] with actual compressed buffer length.

CompressionMiddleware.cs

And above link to realisation of compression middleware contains:

if (context.Response.Headers["Content-Length"].Count > 0)
{
   context.Response.Headers["Content-Length"] = compressed.Length.ToString();
}


来源:https://stackoverflow.com/questions/38268800/asp-net-core-compression-middleware-empty-reponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!