Click here to Skip to main content
15,894,017 members
Articles / Web Development / ASP.NET / ASP.NET Core

ASP.NET Core 2.0 Response Compression

Rate me:
Please Sign up or sign in to vote.
2.25/5 (4 votes)
5 Sep 2017CPOL 5.6K   2  
How to compress responses in ASP.NET Core. Continue reading...

Problem

How to compress responses in ASP.NET Core.

Solution

To an empty project, configure services and middleware for compression in Startup:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddResponseCompression();

            services.AddMvc();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseResponseCompression();

            app.UseMvcWithDefaultRoute();
        }

Add a Home controller with Index action and write some data to the view:

ASP.NET
<h2>ASP.NET Core Response Compression</h2>
@for (int i = 0; i < 10000; i++)
{
    <strong>Testing Response Compression: @i</strong>
}

Notice the size and time of response, before and after compression:

Response Compression - before-after

Discussion

When you’re unable to use the compression features of web servers (IIS, Apache, Nginx), ASP.NET Core provides an alternate option, Response Compression middleware. It’s performance won’t match server based compression features though.

Client will send Accept-Encoding header in its request to indicate compression capabilities. The server will response with Content-Encoding indicating the compression used. Response Compression middleware supports gzip compression by default.

Compression Level

The default level of compression is Fastest, i.e., to compress as quickly as possible. You could change to Optimal for maximum compression:

C#
services.Configure<GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Optimal;
            });

            services.AddResponseCompression(options =>
            {
                options.Providers.Add<GzipCompressionProvider>();
            });

However, notice the size and time! It took more than 1 second (compared to Fastest level) but we didn’t gain a lot in terms of size (0.4kb). You’ll need to test on actual websites to decide the appropriate level.

Response Compression - level

HTTPS Compression

Compression can be enabled for HTTPS by using EnableForHttps however, this could lead to security issues:

C#
services.AddResponseCompression(options =>
            {
                options.EnableForHttps = true;
            });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --