7

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.

        var response = context.Response;


        if (encodingsAccepted.ToArray().Any(x => 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);


        }
user2121006
  • 71
  • 1
  • 3

2 Answers2

14

The detailed description about response compression is available here: https://learn.microsoft.com/en-us/aspnet/core/performance/response-compression

A quick summary
Compression can be enabled in 2 steps:

  1. Add a reference to the Microsoft.AspNetCore.ResponseCompression package.
  2. Enable compression on the application startup:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCompression();
    }
    
    public void Configure(IApplicationBuilder app)
    {
        app.UseResponseCompression();
    
        ...
    }
    

That's it. Now the response will be compressed in case if the client accepts compression encoding.

Alexander Stepaniuk
  • 6,217
  • 4
  • 31
  • 48
  • 3
    Be mindful that if you are using https, you will need to use the `EnableForHttps` option in the `AddResponseCompression` call. Ref: https://learn.microsoft.com/en-us/aspnet/core/performance/response-compression?view=aspnetcore-3.1#compression-with-secure-protocol – Veli Gebrev Oct 02 '20 at 12:18
0

All of that must occur before invoking the next middleware (e.g. _next.Invoke or what have you), then after invoking the next middleware, you should await context.Response.Body.FlushAsync();.

TylerY86
  • 3,737
  • 16
  • 29