Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Enabling GZip Compression in ASP.NET 5

0.00/5 (No votes)
25 Oct 2015 1  
Enabling GZip Compression in ASP.NET 5

Compression is an easy and effective way to reduce the size and increase the speed of communication between a client and remote resource. Two common compression algorithms used on the web are GZip and Deflate. The Accept-Encoding header is used by a client to restrict the encoding types that are acceptable in the response.

Here is the Compression middleware implementation, which whether GZip compression supported by the “Accept-Encoding” header value. If it supports, middleware compress the body and send the compressed stream to the client. Since browser doesn’t know about the content encoding, you need to set the content encoding header value as well.

Here is the middleware implementation.

public class CompressionMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext httpContext)
    {
        var acceptEncoding = httpContext.Request.Headers["Accept-Encoding"];
        if (acceptEncoding != null)
        {
            if (acceptEncoding.ToString().IndexOf
            ("gzip", StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                using (var memoryStream = new MemoryStream())
                {
                    var stream = httpContext.Response.Body;
                    httpContext.Response.Body = memoryStream;
                    await _next(httpContext);
                    using (var compressedStream = new GZipStream(stream, CompressionLevel.Optimal))
                    {
                        httpContext.Response.Headers.Add
                        ("Content-Encoding", new string[] { "gzip" });
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await memoryStream.CopyToAsync(compressedStream);
                    }
                }
            }
        }
    }
}

And here is the helper class, which helps to inject the middleware to the HTTP request pipeline.

public static class CompressionMiddlewareExtensions
{
    public static IApplicationBuilder UseCompression(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CompressionMiddleware>();
    }
}

And you can use this middleware in the Configure method in Startup.cs file, like this:

app.UseCompression();

Happy programming!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here