Compress HTTP responses using Kestrel and .NET core middleware
<p>I'm looking to encode HTTP responses on the fly using .NET Core and the Kestrel web server. The following code does not work, the response fails to load in the browser.</p>

<pre><code>        var response = context.Response;


        if (encodingsAccepted.ToArray().Any(x =&gt; x.Contains("gzip")))
        {
            // Set Gzip stream.
            context.Response.Headers.Add("Content-Encoding", "gzip");
            // Wrap response body in Gzip stream.
            var body = context.Response.Body;


            context.Response.Body = new GZipStream(body, CompressionMode.Compress);


        }
</code></pre>