Response Compression in ASP.NET Core
ASP.NET Core comes with a built-in lightweight web server, also known as Krestal, Usually, you would run this behind an IIS or NGINX Reverse Proxy but it is also possible to use it on its own.
Microsoft introduced Response Compression Middleware in ASP.NETCore as part of ASP.NET Core 1.1.
To start using the Microsoft.AspNetCore.ResponseCompression
Middleware, first, we have to get the NuGet Package in our project, but before that let’s create a mvc
project.
Run the command
dotnet new mvc
Once done, run the following command to install the response compression Middleware.
dotnet add package Microsoft.AspNetCore.ResponseCompression
Now let’s run the application, once the application starts running, Opening developer tools in Chrome(I prefer chrome developer tools, if you’re using some other browsers then you can use their respective developer tool). Now go to Network tab and check the Size column, you’ll probably be seeing something like below
As you can see in the size column you’re getting contents of whatever its size is, which mean its an uncompressed response. Now let’s make it a compressed response.
Open the Startup.cs
file and navigate to ConfigureServices
Method. As this method will be called in run-time so if we want to add any external services then its best to call this method. As we are also adding a service so we will be also hooking our service to this method.
Let’s add the following code to the ConfigureServices
method
services.Configure(options => options.Level = CompressionLevel.Fastest);
services.AddResponseCompression(options =>
{
options.Providers.Add();
});
You have to add the following namespaces to make the added code work
using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;
Now let’s tell the Configure
method to use ResponseCompression
, through Configure
method we can notify changes to HTTP Request pipeline.
app.UseResponseCompression();
All set, Let’s re-run the application again and check the developer tools network tab. You’ll be seeing something like this.
Notice for Content-Encoding we are using gzip
Also, you can see the contents size has been compressed. So in a real-time situation where you’ll be sending a lot of data to the client then content compression can improve the performance a lot.
You can find complete code of this on GitHub under this Repository.
Thanks for reading the article, if you’ve liked it then please leave a comment so it will encourage me to write further.