Response Compression Middleware In ASP.NET Core

ASP.NET Core 1.1 has an inbuilt Response Compression Middleware for compression, which by default uses GZIP compression. In simple words, GZIP is a technique, which is used for the file compression and decompression for faster network transfer.

All the modern Browsers support response compression. Using GZIP Compression is the best approach to reduce the response size and provide better speed for transferring the files over the network.

Enable GZIP compression in ASP.NET Core

Let's first install GZIP in our ASP.NET MVC Project, using NUGET Package Manager.

Step 1

Right click on ASP.NET Core and select Manage Nuget Package.

 Response Compression Middleware in ASP.NET Core by Nishan Aryal

Step 2

Browse Microsoft.AspNetCore.ResponseCompression.

Response Compression Middleware in ASP.NET Core by Nishan Aryal 

Once ResponseCompression is installed, we need to configure it.

Let's open Startup.cs file and add the code given below in ConfigurationService method.

Response Compression Middleware in ASP.NET Core by Nishan Aryal

Code snippet
 
  1. // This method gets called by the runtime. Use this method to add services to the container.  
  2.         public void ConfigureServices(IServiceCollection services)  
  3.         {  
  4.             // Add framework services.  
  5.             services.AddDbContext<ApplicationDbContext>(options =>  
  6.                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  7.   
  8.             services.AddIdentity<ApplicationUser, IdentityRole>()  
  9.                 .AddEntityFrameworkStores<ApplicationDbContext>()  
  10.                 .AddDefaultTokenProviders();  
  11.   
  12.             //Add ResponseCompression as Service 
  13.  
  14.             services.AddResponseCompression();
  15.   
  16.             services.AddMvc();  
  17.   
  18.             // Add application services.  
  19.             services.AddTransient<IEmailSender, AuthMessageSender>();  
  20.             services.AddTransient<ISmsSender, AuthMessageSender>();  
  21.         }  
By default, ASP.NET Core uses GZIP compression. Now, let’s add this middleware to HTTP pipeline, so add the line of code given below in Configure method of Startup.cs.

Remember to add Compression middleware before other middlewares, which serves the files.

Response Compression Middleware in ASP.NET Core by Nishan Aryal 

Code snippet 
  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  2.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  3.         {  
  4.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  5.             loggerFactory.AddDebug();  
  6.               
  7.             if (env.IsDevelopment())  
  8.             {  
  9.                 app.UseDeveloperExceptionPage();  
  10.                 app.UseDatabaseErrorPage();  
  11.                 app.UseBrowserLink();  
  12.             }  
  13.             else  
  14.             {  
  15.                 app.UseExceptionHandler("/Home/Error");  
  16.             }  
  17.             app.UseStaticFiles();  
  18.             app.UseIdentity();  
  19.             // Add external authentication middleware below.  
  20.             //Compression middleware before other middlewares which serves the files.
  21.   
  22.             app.UseResponseCompression();   
  23.   
  24.             app.UseMvc(routes =>  
  25.             {  
  26.                 routes.MapRoute(  
  27.                     name: "default",  
  28.                     template: "{controller=Home}/{action=Index}/{id?}");  
  29.             });  
  30.         }  
So far we have installed and configured Response Compression in ASP.NET Core Application.
 
Creating dummy data for Test
 
Lets create a Test API to assess the data.

My TestAPI looks like, as shown below.
 
Response Compression Middleware in ASP.NET Core by Nishan Aryal 
 
Code snippet 
  1. //[Route("api/TestAPI/Get")]  
  2.        [HttpGet]  
  3.        public IEnumerable<string> Get()  
  4.        {  
  5.            List<string> data = new List<string>();  
  6.            for (int i = 1; i <= 100; i++)  
  7.            {  
  8.                data.Add("ID :" + i.ToString());  
  9.                data.Add("Name :" + i.ToString());  
  10.                data.Add("Address :" + i.ToString());  
  11.                data.Add("Email :" + i.ToString());  
  12.                data.Add("Telephone :" + i.ToString());  
  13.            }  
  14.            return data;  
  15.        }   
Application execution

Lets run the Application and navigate to API.
 
In my case, it is http://localhost:51381/TestAPI/Get  
 
Case I
 
When Response Compression is disabled.

(Comment below lines in Startup.cs) 
  • services.AddResponseCompression(); (ConfigureServices method)
  • app.UseResponseCompression(); (Configure Method)
Response Compression Middleware in ASP.NET Core by Nishan Aryal
 
Case II
 
When Response Compression is enabled.

(UnComment below lines in Startup.cs)
  • services.AddResponseCompression(); (ConfigureServices method)
  • app.UseResponseCompression(); (Configure Method)
 Response Compression Middleware in ASP.NET Core by Nishan Aryal
 
 
Comparision

   Response Compression Disabled  Response Compression Enabled
 Transferred data 6.4 KB 1.4 KB
 Finish time 32 ms 14 ms
 Load time 135ms 81 ms
 
Summary

Thus we learned,
  • How to install Response Compression library in ASP.NET Core.
  • How to enable Response Compression as middleware.
  • How to transfer the data over the network by compressing. 
  • Decrease Transfer and Load time of the data. 
You may also like