Compressing Web API Response Using DotNetZip

Why to Compress Web API Response?
 
Web API compression is very important to improve ASP.NET Web API performance. In the Web, the data transfers through the network in packages (data packets), increasing the size of the data package, which will increase the size as well as increase the response time of the Web API. Thus, reducing the data packet size improves the load performance of Web API.

By compressing the API Response, we have the following two advantages. 
  1. Data size will be reduced
  2. Response time will increase (increasing the speed of the communication between the Client and Server.
Thus, in this article, I will show how to compress the Web API response to decrease the size of the data and increase the speed of the communication between the Server and Client.
 
In my Web API project, I have an Account Controller and in it, I am adding one Method called getData, as shown below:
  1.        [HttpGet]  
  2.        [Route("getData")]  s
  3.        [AllowAnonymous]  
  4.         
  5.        public async Task<IHttpActionResult> getData()  
  6.        {  
  7.            Stopwatch sw=new Stopwatch();  
  8.            sw.Start();  
  9.            Dictionary<object, object> dict = new Dictionary<object, object>();  
  10.            List<Employee> li = new List<Employee>();  
  11.            li.Add(new Employee {id="2",Name="Debendra",Id= "A123", Email="[email protected]"});  
  12.            li.Add(new Employee { id = "3", Name = "Sumit", Id = "A124", Email = "[email protected]" });  
  13.            li.Add(new Employee { id = "4", Name = "Jayant", Id = "A125", Email = "[email protected]" });  
  14.            li.Add(new Employee { id = "5", Name = "Kumar", Id = "A126", Email = "[email protected]" });  
  15.       
  16.         
  17.            sw.Stop();  
  18.             
  19.            dict.Add("Details",li);  
  20.            dict.Add("Time", sw.Elapsed);  
  21.   
  22.            return Ok(dict);  
  23.   
  24.        }  
Thus, I have created an employee list detail and want to return it as a response. Here, I have used StopClock class to measure the response time. Let's check the API, using the Postman client.



To check the size of the data, go to the header section and check the content-length.

 

Content-Length

The content-length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient; or, in the case of the Head method, the size of the entity-body that would have been sent; had the request been a Get.

Now, lets use Gzip to compress the API response. For this, please add the following dll from NuGet-Package as follows:

 

Now, add the following class "DeflateCompression" in your project, which is derived from "ActionFilterAttribute", as follows: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net.Http;  
  6. using System.Web;  
  7. using System.Web.Http.Filters;  
  8.   
  9. namespace Webapi2  
  10. {  
  11.      
  12.   
  13.       public class DeflateCompressionAttribute : ActionFilterAttribute  
  14.       {  
  15.     public override void OnActionExecuted(HttpActionExecutedContext actContext)  
  16.    {  
  17.        var content = actContext.Response.Content;  
  18.        var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;  
  19.        var zlibbedContent = bytes == null ? new byte[0] :   
  20.        CompressionHelper.DeflateByte(bytes);  
  21.        actContext.Response.Content = new ByteArrayContent(zlibbedContent);  
  22.        actContext.Response.Content.Headers.Remove("Content-Type");  
  23.        actContext.Response.Content.Headers.Add("Content-encoding""deflate");  
  24.        actContext.Response.Content.Headers.Add("Content-Type","application/json");  
  25.        base.OnActionExecuted(actContext);  
  26.      }  
  27.   
  28.             }  
  29.   
  30.         public class CompressionHelper  
  31.         {  
  32.   
  33.             public static byte[] DeflateByte(byte[] str)  
  34.             {  
  35.   
  36.                 if (str == null)  
  37.                 {  
  38.   
  39.                     return null;  
  40.   
  41.                 }  
  42.   
  43.                 using (var output = new MemoryStream())  
  44.                 {  
  45.   
  46.                     using (  
  47.   
  48.                     var compressor = new Ionic.Zlib.GZipStream(  
  49.   
  50.                     output, Ionic.Zlib.CompressionMode.Compress,  
  51.   
  52.                     Ionic.Zlib.CompressionLevel.BestSpeed))  
  53.                     {  
  54.   
  55.                         compressor.Write(str, 0, str.Length);  
  56.   
  57.                     }  
  58.   
  59.                     return output.ToArray();  
  60.   
  61.                 }  
  62.   
  63.             }  
  64.   
  65.         }    
  66.     }  
Now, use the "[DeflateCompression]" in the  method, as follows: 
  1. [HttpGet]  
  2.        [Route("getData")]  
  3.        [AllowAnonymous]  
  4.        [DeflateCompression]  
  5.        public async Task<IHttpActionResult> getData()  
  6.        {  
  7.            Stopwatch sw=new Stopwatch();  
  8.            sw.Start();  
  9.            Dictionary<object, object> dict = new Dictionary<object, object>();  
  10.            List<Employee> li = new List<Employee>();  
  11.            li.Add(new Employee {id="2",Name="Debendra",Id= "A123", Email="[email protected]"});  
  12.            li.Add(new Employee { id = "3", Name = "Sumit", Id = "A124", Email = "[email protected]" });  
  13.            li.Add(new Employee { id = "4", Name = "Jayant", Id = "A125", Email = "[email protected]" });  
  14.            li.Add(new Employee { id = "5", Name = "Kumar", Id = "A126", Email = "[email protected]" });  
  15.      
  16.            sw.Stop();  
  17.             
  18.            dict.Add("Details",li);  
  19.            dict.Add("Time", sw.Elapsed);  
  20.   
  21.            return Ok(dict);  
  22.   
  23.        }  
Now, please run the project and check the result by calling the Web API.

 

Now, check the size of the data after compressing.

 
Here, I am showing the response before compressing and after compressing the data as follows:

result

Thus, by using this DotNetZip  compression, we can compress more then 50 percent of the data and reduce the response, time which is very, very important for  Web API.

Up Next
    Ebook Download
    View all
    Learn
    View all