TRUNGTQ

Think Big, Act Small, Fail Fast and Learn Rapidly

NAVIGATION - SEARCH

Compressing Web API Responses Using DotNetZip

Web API is very popular for building RESTful Web Services in .NET and performance always plays a vital role in any application. In case of large data which is going through the network traffic, it will decrease the performance of the application.

Compression is a good technique to reduce the size of response data and increase the speed of communication between a client and remote resource.

Here, we are going to use DotNetZip Library to compress the response size. We will go step by step for compressing the response of Web API using DotNetZip Library.

Open Visual Studio and click on File -> New -> Project, as in the below image.

Choose ASP.NET Web Application and enter the name as "CompressingWebAPIResponse" and click OK.


Select Empty from the templates, check the Web API checkbox list, and click OK.

Go to the Solution Explorer and right click on Controllers -> Add -> Controller for creating the Controller for Web API.

Select the Web API 2 Controller - Empty from the scaffold and click "Add" .

Enter the Controller name as EmployeeController.

Similarly, add one Model class as Employee.cs inside Models folder and write some property in this class.

 
  1. public class Employee  
  2.     {  
  3.         public string Id { get; set; }  
  4.         public string Name { get; set; }  
  5.         public string Address{ get; set; }  
  6. }   

Now, add one GET Action method in the EmployeeController for getting all the records as below.

 
  1. public IHttpActionResult GetEmployeeData()  
  2.         {  
  3.             List<Employee> employee = new List<Employee>  
  4.             {  
  5.                 new Employee { Id = "1", Name = "Vivek", Address = "Hyderabad" },  
  6.                 new Employee { Id = "2", Name = "Ranjeet", Address = "Hyderabad" },  
  7.                 new Employee { Id = "3", Name = "Ganesh", Address = "Hyderabad" },  
  8.                 new Employee { Id = "4", Name = "Gajanan", Address = "Hyderabad" },  
  9.                 new Employee { Id = "5", Name = "Vijay", Address = "Hyderabad" },  
  10.                 new Employee { Id = "6", Name = "Ashish", Address = "Hyderabad" },  
  11.                 new Employee { Id = "7", Name = "Praveen", Address = "Hyderabad" },  
  12.                 new Employee { Id = "8", Name = "Santosh", Address = "Hyderabad" }  
  13.             };  
  14.   
  15.             return Ok(employee);  
  16.         }  

Now, using Postman, call this Get method and see the expected data as below.

Click on the Header tab and see the Content-Length in below image.

Now, we are going to see content size after additionof DotnetZip Library and using compression technique.

First of all, we have to install DotnetZip Library through "Manage NuGet packages".

Now, add one new folder as Filters and add one class inside this folder as GzipCompression.cs.

Write the below code in this page.

 
  1. using System.IO;  
  2. using System.Net.Http;  
  3. using System.Web.Http.Filters;  
  4.   
  5. namespace CompressingWebAPIResponse.Filters  
  6. {  
  7.     public class GzipCompressionAttribute : ActionFilterAttribute  
  8.     {  
  9.         public override void OnActionExecuted(HttpActionExecutedContext actionContext)  
  10.         {  
  11.             var content = actionContext.Response.Content;  
  12.             var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;  
  13.             var zlibbedContent = bytes == null ? new byte[0] :  
  14.             CompressionHelper.GzipByte(bytes);  
  15.             actionContext.Response.Content = new ByteArrayContent(zlibbedContent);  
  16.             actionContext.Response.Content.Headers.Remove("Content-Type");  
  17.             actionContext.Response.Content.Headers.Add("Content-encoding""gzip");  
  18.             actionContext.Response.Content.Headers.Add("Content-Type""application/json");  
  19.             base.OnActionExecuted(actionContext);  
  20.         }  
  21.     }  
  22.   
  23.     public class CompressionHelper  
  24.     {  
  25.         public static byte[] GzipByte(byte[] str)  
  26.         {  
  27.             if (str == null)  
  28.             {  
  29.                 return null;  
  30.             }  
  31.   
  32.             using (var output = new MemoryStream())  
  33.             {  
  34.                 using (var compressor = new Ionic.Zlib.GZipStream(output, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestSpeed))  
  35.                 {  
  36.                     compressor.Write(str, 0, str.Length);  
  37.                 }  
  38.                 return output.ToArray();  
  39.             }  
  40.         }  
  41.     }  
  42. }  

In the code given above, we are inheriting the ActionFilterAttribute class for overriding OnActionExecuted Method and we also need a helper class to perform compression.

Now, just put this ActionFilter attribute above the GetEmployeeData method, as shown below.

 
  1. [GzipCompression]  
  2.         public IHttpActionResult GetEmployeeData()  
  3.         {  
  4.             List<Employee> employee = new List<Employee>  
  5.             {  
  6.                 new Employee { Id = "1", Name = "Vivek", Address = "Hyderabad" },  
  7.                 new Employee { Id = "2", Name = "Ranjeet", Address = "Hyderabad" },  
  8.                 new Employee { Id = "3", Name = "Ganesh", Address = "Hyderabad" },  
  9.                 new Employee { Id = "4", Name = "Gajanan", Address = "Hyderabad" },  
  10.                 new Employee { Id = "5", Name = "Vijay", Address = "Hyderabad" },  
  11.                 new Employee { Id = "6", Name = "Ashish", Address = "Hyderabad" },  
  12.                 new Employee { Id = "7", Name = "Praveen", Address = "Hyderabad" },  
  13.                 new Employee { Id = "8", Name = "Santosh", Address = "Hyderabad" }  
  14.             };  
  15.   
  16.             return Ok(employee);  
  17.         }  

Below is the image of the same request with compressed data using gzip compression.

Here, we can clearly see the difference of Content-Length which is changed from 395 to 144. We can also use this code for Controller level compression as per our requirement.

In this easy way, we can compress large response data and increase the application performance.

LINK: http://www.c-sharpcorner.com/article/compressing-web-api-responses-using-dotnetzip/