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