Click here to Skip to main content
15,888,968 members
Articles / Web Development / HTML
Technical Blog

Enabling GZip Compression in ASP.NET5

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
31 Oct 2015MIT 7.9K   3   3
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.

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.

<code class="language-csharp" data-lang="csharp"> 1 public class CompressionMiddleware
 2 {
 3     private readonly RequestDelegate _next;
 4 
 5     public CompressionMiddleware(RequestDelegate next)
 6     {
 7         _next = next;
 8     }
 9 
10     public async Task Invoke(HttpContext httpContext)
11     {
12         var acceptEncoding = httpContext.Request.Headers["Accept-Encoding"];
13         if (acceptEncoding != null)
14         {
15             if (acceptEncoding.ToString().IndexOf("gzip", StringComparison.CurrentCultureIgnoreCase) >= 0)
16             {
17                 using (var memoryStream = new MemoryStream())
18                 {
19                     var stream = httpContext.Response.Body;
20                     httpContext.Response.Body = memoryStream;
21                     await _next(httpContext);
22                     using (var compressedStream = new GZipStream(stream, CompressionLevel.Optimal))
23                     {
24                         httpContext.Response.Headers.Add("Content-Encoding", new string[] { "gzip" });
25                         memoryStream.Seek(0, SeekOrigin.Begin);
26                         await memoryStream.CopyToAsync(compressedStream);
27                     }
28                 }
29             }
30         }
31     }
32 }</code>

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

<code class="language-csharp" data-lang="csharp">1 public static class CompressionMiddlewareExtensions
2 {
3     public static IApplicationBuilder UseCompression(this IApplicationBuilder builder)
4     {
5         return builder.UseMiddleware<CompressionMiddleware>();
6     }
7 }</code>

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

<code class="language-csharp" data-lang="csharp">1 app.UseCompression();</code>

Happy Programming

This article was originally posted at http://dotnetthoughts.net/feed.xml

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

 
QuestionJust as an FYI... Pin
avanschaick7-Dec-15 3:11
avanschaick7-Dec-15 3:11 
GeneralMy vote of 4 Pin
Sebastiaan Lubbers4-Nov-15 22:22
professionalSebastiaan Lubbers4-Nov-15 22:22 
Question5 here Pin
237412-Nov-15 13:02
237412-Nov-15 13:02 

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.