Enable Response Compression in ASP.NET Core in 5 Easy Steps
As an ASP.NET developer you are probably aware that IIS comes with its own
compression module that can effectively compress the response content. This can
dramatically reduce the network bytes giving good performance benefits. However,
what if you aren't using IIS at all? Luckily, ASP.NET Core offers you a
middleware that can compress the response content for you. In this article you
will learn to configure the ASP.NET Core response compression middleware in your
1. Create a new ASP.NET Core web application
Begin by creating a new ASP.NET Core web application. You can use the Web
Application template so that the basic startup configuration is already done for
2. Add ASP.NET Core Response Compression NuGet package
Once the web application is created you need to add a NuGet package that does
the compression for you. To do that right click on the References folder and
pick Manage NuGet packages shortcut menu option. This will open the NuGet
packages tab. Search for Response Compression and you will se this entry :
The Microsoft.AspNetCore.ResponseCompression package is what you need to
enable the response compression. Click on the Install button and install the
3. Add the Response Compression service to your application
Next, open the Startup.cs file and modify the ConfigureServices() method as
shown below :
public void ConfigureServices(IServiceCollection services)
(options => options.Level = CompressionLevel.Optimal);
Here, you first configure the GzipCompressionProviderOptions so that highest
level of compression is used. Then you ad the response compression service using
the AddResponseCompression() method. While calling the AddResponseCompression()
method you specify Gzip compression in the options.
4. Add the Response Compression middleware to the request pipeline
Then go to the Configure() method and add the response compression middleware
to the request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
Note that the UseResponseCompression() method that adds the middleware is
being called before any of the other UseXXXXX() methods. This way the middleware
gets chance to compress the response.
5. Verify that the response is being compressed
This completes the configuration. Run the application and observe the
response in F12 tools (or equivalent). You will find that the Content-Encoding
header is set to gzip as expected.
For more information about response compression go
That's it for now! Keep coding!!