Response Compression is if client browser supports response compression, the server sends the content compressed, so the response size is reduced. There are couple of compression schemes, but almost all the browsers supports gzip and deflate. In this post let’s see how you can use Response Compression Middleware in an ASP.NET Core application to serve the content compressed using gzip.
I am going to use Visual Studio 2017 RC and let’s create an ASP.NET Core Web Application targeting .NET Core and I am selecting the template as Web API as I want to simulate large content being sent to the client.
Once the project is created and all the dependencies are restored, let’s update all our dependencies to ASP.NET Core 1.1. Please note that Visual Studio 2017 RC targets ASP.NET Core 1.0.1 for it’s default ASP.NET Core templates as it’s the LTS (Long Term Support) version as of now.
Once update is completed, let’s modify Get() action in default ValuesController to return some large set of data.
Now let’s just run the application, trigget Get() action in ValuesController and explore the request and response information.
First if we examine the request headers, it looks likes follows.
I am using Chrome and it seems that my current version of Chrome supports set of compression types. But in the response there was no indication the content which got received is compressed.
Size of the content received is 1.2 MB.
Now let’s add some code to send the content compressed using gzip. Let’s add a new nuget package to the project and that is Microsoft.AspNetCore.ResponseCompression.
Now let’s modify the ConfigureServices method and Configure method in startup.cs to add and use Response Compression Middleware.
You will need to add the following using.
Now let’s run the application again, trigget Get() action in ValuesController and examine the request and response.
|Request and Reponse Headers|
Request is obviously the same and now you can see that response is being compressed using gzip.
And this time only 238 KB was transferred. 1.2 MB has been reduced to 238 KB.Happy Coding.