Click here to Skip to main content
14,173,566 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

18.1K views
3 bookmarked
Posted 25 Oct 2015
Licenced MIT

Enabling GZip Compression in ASP.NET 5

, 25 Oct 2015
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The MIT License

Share

About the Author

Anuraj Parameswaran
Technical Lead
India India
Working as Tech. Lead

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

You may also be interested in...

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
memberThomas Jørgensen8-Jun-16 1:56 
QuestionPlace it to first Middleware Pin
ZOXEXIVO12-Feb-16 3:34
memberZOXEXIVO12-Feb-16 3:34 
Suggestionadd System.IO.Compression in dependencies of project.json Pin
Oleg Kiriljuk8-Nov-15 3:27
memberOleg 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
memberAnuraj 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190524.3 | Last Updated 25 Oct 2015
Article Copyright 2015 by Anuraj Parameswaran
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid