Click here to Skip to main content
15,884,388 members
Articles / Web Development / HTML

Enabling GZip Compression in ASP.NET 5

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
25 Oct 2015MIT 26.8K   3   7
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.

C#
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.

C#
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:

C#
app.UseCompression();

Happy programming!

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Technical Lead
India India
Working as Tech. Lead

My blog : dotnetthoughts.net.
You can follow me in twitter : @anuraj

Comments and Discussions

 
QuestionHow to use it with IAppBuilder Pin
M. Salah AbdAllah15-Feb-17 18:15
professionalM. Salah AbdAllah15-Feb-17 18:15 
QuestionModification Pin
Thomas Jørgensen8-Jun-16 1:56
Thomas Jørgensen8-Jun-16 1:56 
QuestionPlace it to first Middleware Pin
ZOXEXIVO12-Feb-16 3:34
ZOXEXIVO12-Feb-16 3:34 
Suggestionadd System.IO.Compression in dependencies of project.json Pin
Oleg Kiriljuk8-Nov-15 3:27
Oleg Kiriljuk8-Nov-15 3:27 
QuestionHow to use it in MVC? Pin
Tridip Bhattacharjee26-Oct-15 4:38
professionalTridip Bhattacharjee26-Oct-15 4:38 
AnswerRe: How to use it in MVC? Pin
Anuraj Parameswaran28-Oct-15 3:40
Anuraj Parameswaran28-Oct-15 3:40 
GeneralRe: How to use it in MVC? Pin
Tridip Bhattacharjee28-Oct-15 21:39
professionalTridip Bhattacharjee28-Oct-15 21:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.