DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Implementing Cache Dependency in ASP.NET Core
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Providing Enum Consistency Between Application and Data
  • Deploying AI With an Event-Driven Platform

Trending

  • Scalable System Design: Core Concepts for Building Reliable Software
  • Google Cloud Document AI Basics
  • Emerging Data Architectures: The Future of Data Management
  • GDPR Compliance With .NET: Securing Data the Right Way
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. ASP.NET Core Response Compression

ASP.NET Core Response Compression

In this blog post, we show how to make response compression work in ASP.NET Core with the help of Brotli. Read on to get started!

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Feb. 20, 19 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
26.8K Views

Join the DZone community and get the full member experience.

Join For Free

ASP.NET Core supports response compression. From popular algorithms, gzip and Brotli are supported. Those who like can also implement their own response compression providers. This blog post shows how response compression works in ASP.NET Core.

With ASP.NET Core we have three options for compression:

  1. ASP.NET Core does the compression.
  2. The ront-end web server does the compression.
  3. Static files are precompressed.

We can skip the second and third options here because we are interested in how ASP.NET Core carries out response compression. Those who don't use the Microsoft.AspNetCore.App metapackage must add a reference to the Microsoft.AspNetCore.ResponseCompression NuGet package to enable response compression.

Test Page

I'm using a simple test page for this guide. Not much content, not many files, and the effects of compression are easy to see and compare.

By default, without any compression the page loads as shown in the image below.

When read from cache the numbers are different.

I start with a table to visualize the effects of the response compression better.

Let's leave these numbers here for a moment and make the compression work.

gzip

Let's get started with gzip compression as it comes out-of-box. No tricks, no miracles. First we have to set the option for compression and then add the compression to request the middleware pipeline. We do it in the ConfigureServices() method of the Startup class.

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

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

For HTTPS, we have to say when we want to use compression due to CRIME and BREACH security exploits.

There are three possible values for compression level:

  • NoCompression - compression is ignored.
  • Optimal - golden way between compression level and CPU resources (default).
  • Fastest - compressing with minimal effects on server load.

Next we have to modify the Configure() method of the Startup class.

app.UseStaticFiles();

// Enable compression
app.UseResponseCompression();

app.UseMvc(routes =>
{
     routes.MapRoute(
         name: "default",
         template: "{controller=Home}/{action=Index}/{id?}");
});

BUG! I made one bad mistake in the code above but let's get to it later as it doesn't affect what we are doing right now.

Let's try to load the page with both compession levels. We start with the fastest compression and then try for the optimal compression.

gzip with the fastest compression level

gzip with the optimal compression level

And let's write the results to table.

Compression Response size (KB) %
No compression 764.99 100.00
No compression, from cache 11.25 1.47
gzip, fastest 652.62 85.31
gzip, optimal 652.43 85.23

The numbers are very similar for both compression levels. It should ring an alarm for those readers who have worked with response compression before. But we'll get to that later.

Brotli

Brotli is new open-source compression algorithm supported by almost all major browsers. It provides better compression than gzip. More information about browser support for Brotli is available at Can I Use.

On our application side there's nothing very much different. We already have everything configured and introducing Brotli is easy. We have to configure its options and add Brotli's compression provider to the response compression provider's collection.

services.Configure<BrotliCompressionProviderOptions>(options =>
{
     options.Level = CompressionLevel.Optimal;
});

services.AddResponseCompression(options =>
{
     options.EnableForHttps = true;     options.Providers.Add<BrotliCompressionProvider>();
});

With brotli enabled, let’s also create two tests – one with each compression level.

Brotli with the fastest compression level

Brotli with the optimal compression level

Let's add these results to table.

Compression Response size (KB) %
No compression 764.99 100.00
No compression, from cache 11.25 1.47
gzip, fastest 652.62 85.31
gzip, optimal 652.43 85.23
Brotli, fastest 652.74 85.32
Brotli, optimal 651.83 85.21

The results are almost on the same level as gzip, and this seems weird to me. Why introduce a new compression algorithm if the benefits are so small? Okay, time to confess...

Compressing Static Files

I did great on sweeping some dust under the carpet before and I didn't stop on the closed investigation of static files. Let's run the application and see some static files.

Image title

They're not compressed. Why? The question comes down to the request middleware ordering in the application's start-up. We have to put compression before static files in the Configure() method. Otherwise, the static files' middleware finds a static file and returns it immediately.

// Enable compression
app.UseResponseCompression();
app.UseStaticFiles();

app.UseMvc(routes =>
{
     routes.MapRoute(
         name: "default",
         template: "{controller=Home}/{action=Index}/{id?}");
});

With static files properly managed, let's run the application again to see the results.

Compression Response size (KB) %
No compression 764.99 100.00
No compression, from cache 11.25 1.47
gzip, fastest 289.92 37.90
gzip, optimal 268.92 35.15
Brotli, fastest 293.74 38.40
Brotli, optimal 252.65 33.03

When we compare the results, we can see more differences. Brotli with optimal compression is faster and it gives even more effect when the responses used are bigger than the ones I had.

Controlling Compression of Static Files

By default, these MIME-types are compressed:

  • application/javascript
  • application/json
  • application/xml
  • text/css
  • text/html
  • text/json
  • text/plain

When configuring response compression, we can specify our own list of types to compress.

services.AddResponseCompression(options =>
{
     IEnumerable<string> MimeTypes = new[]
     {
         // General
         "text/plain",
         "text/html",
         "text/css",
         "font/woff2",
         "application/javascript",
         "image/x-icon",
         "image/png"
     };

     options.EnableForHttps = true;
     options.MimeTypes = MimeTypes;
     options.Providers.Add<GzipCompressionProvider>();
     options.Providers.Add<BrotliCompressionProvider>();
});

Similar way we can exclude set of MIME-types from compression.

services.AddResponseCompression(options =>
{     IEnumerable<string> MimeTypes = new[]
     {
         // General
         "text/plain",
         "text/html",
         "text/css",
         "font/woff2",
         "application/javascript",
         "image/x-icon",
         "image/png"
     };

     options.EnableForHttps = true;
     options.ExcludedMimeTypes = MimeTypes;
     options.Providers.Add<GzipCompressionProvider>();
     options.Providers.Add<BrotliCompressionProvider>();
});

Having a list of allowed types doesn't mean that compression happens. When activated, then compression is use based on the browser's Accept-Encoding header. If this header doesn't specify any known compression algorithm then ASP.NET Core doesn't compress the requested file.

Wrapping Up

Response compression can save us a lot of traffic when applied to a ASP.NET Core web application. Public interface of the response compression API is simple and flexible. We can control compression levels and the MIME-types to be compressed. For static files, we have to include response compression before static files' middleware because otherwise it will not run. And, as we saw, the new Brotli compression is better than the older gzip versoin.

ASP.NET ASP.NET Core Database Fastest application Open source Algorithm Middleware Cache (computing)

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Implementing Cache Dependency in ASP.NET Core
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Providing Enum Consistency Between Application and Data
  • Deploying AI With an Event-Driven Platform

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: