Joydip Kanjilal
Contributor

How to use Brotli for response compression in ASP.Net Core

how-to
Jun 11, 20184 mins
Small and Medium BusinessSoftware DevelopmentWeb Development

Take advantage of ASP.Net Core’s support for response compression middleware to get more compression in less time using Brotli

super fast gigabit internet speed
Credit: Thinkstock

When working with RESTful services that leverage the ASP.Net Core Web API, the easy availability of CPU versus the scarcity of network bandwidth can be a good reason to use content compression. Content compression reduces bandwidth consumption and facilitates faster responses. Thus you can take advantage of response compression middleware in ASP.Net Core to improve your application’s performance.

There are many response compression frameworks available for use with .Net Core. Brotli is a relatively new compression algorithm that provides much improved compression results over Gzip or Deflate, and it is supported by most modern day web browsers including Google Chrome, Mozilla Firefox, Opera, and Microsoft Edge. This article presents a discussion on how we can work with Brotli in ASP.Net Core.

Getting started with Brotli in ASP.Net Core

The first thing you need to do is create a new ASP.Net Core project in Visual Studio. You should also ensure that the latest version of .Net Core is installed in your system. At the time of this writing, the latest version is .Net Core 2.1. Next, follow these steps to create an ASP.Net Core application in Visual Studio.

  1. In the Visual Studio IDE, click on File > New > Project.
  2. Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates displayed.
  3. Specify a name for the project.
  4. Click OK to save.
  5. Next, in the “New .Net Core Web Application…” window, select “API.”
  6. Specify “ASP.NET Core 2.1” as the version of the ASP.Net Core runtime to be used.
  7. Uncheck the “Enable Docker Support,” “Configure for HTTPS,” and “No Authentication” checkboxes. We won’t be needing these features.
  8. Click OK.

The result should be a new ASP.Net Core project with an example Controller to build and execute RESTful HTTP services.

Implementing a response compression provider in ASP.Net Core

The client uses the Accept-Encoding header to restrict encoding types in the response. The response compression middleware in ASP.Net Core inspects the request headers to see if there is a compression provider available to handle one of the accepted encodings. The ASP.Net Core response compression middleware uses Gzip compression by default, but you can override this behavior to use custom middleware. In this section we’ll explore how we can build a custom compression provider using Brotli.

To get started using Brotli in your ASP.Net Core project, install the Brotli.Net NuGet package via the NuGet package manager. Now, create a class named CustomCompressionProvider that extends the ICompressionProvider interface and implements the CreateStream method as shown below.

public class CustomCompressionProvider : ICompressionProvider
    {
        public string EncodingName => “br”;
        public bool SupportsFlush => true; 
        public Stream CreateStream(Stream outputStream)
        {
            return new BrotliStream(outputStream,
             CompressionLevel.Fastest, false);
        }
    }

Note the usage of CompressionLevel.Fastest to ensure optimal speed. The other possible values are CompressionLevel.NoCompression and CompressionLevel.Optimal. While the former will disable compression, the latter will provide the maximum compression. Naturally, there is always a trade-off between compression level and the time taken to compress content.

Configuring response compression in ASP.Net Core

To configure Brotli to use with your ASP.Net Core application, you need to take advantage of the Startup class. This class has two methods, Configure and ConfigureServices. The following code snippet illustrates how you can turn on response compression.

public void Configure(IApplicationBuilder app)
    {
        app.UseResponseCompression();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }

Next, you should specify the response compression middleware to be used. Here’s how.

services.AddResponseCompression(options =>
        {
            options.Providers.Add(new CustomCompressionProvider());
        });

The following is the complete code listing of the Startup class for your reference.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddResponseCompression(options =>
        {
            options.Providers.Add(new CustomCompressionProvider());
        });
    }
    public void Configure(IApplicationBuilder app)
    {
        app.UseResponseCompression();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }
}

And that’s it. Now when you run your ASP.Net Core Web API services you will see the responses compressed.

The response compression middleware in ASP.Not Core provides an elegant way to compress responses using custom compression algorithms. Brotli not only can provide about 20 percent better compression than Gzip, but it is also about 20 times faster at decompressing content.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author