Foreword

Compression can greatly reduce the response speed of our web server, compression to improve the loading speed of our web pages, and save a certain amount of bandwidth.

When to use the appropriate compression middleware

Server-based response compression is used in IIS, Apache, and Nginx. The execution of the middleware may not match the server module. HTTP.sys and Kestrel server do not currently offer built-in compression support.

When to use Response Compression Middleware:
  • When the following server-based compression techniques are not available:
  1. IIS Dynamic Compression Module
  2. Apache’s GZIP compression
  3. Nginx compression
  • Direct hosting:
  1. Http.sys server
  2. Kestrel server

How to add MIME

The middleware specifies a default set of MIME types for compression:

  • application/javascript
  • application/json
  • application/xml
  • text/css
  • text/html
  • text/json
  • text/plain
  • text/xml
Copy        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCompression();
            services.AddRazorPages();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            app.UseResponseCompression();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

The default is to use Brotli compression

Brotli is a generic-purpose lossless compression algorithm that compresses data using a combination of a modern variant of the LZ77 algorithm, Huffman coding and 2nd order context modeling, with a compression ratio comparable to the best currently available general-purpose compression methods. It is similar in speed with deflate but offers more dense compression.

Brotli is a modern variant based on the LZ77 algorithm, Huffman coding and second-order context modeling. In September 2015, Google software engineers released an enhanced version of Brotli with universal lossless data compression, with a special focus on HTTP compression. The encoder is partially rewritten to increase the compression ratio, both the encoder and the decoder are speeded up, and the streaming API has been improved to add more compression quality levels.

Unlike common general-purpose compression algorithms, Brotil uses a predefined 120-kilobyte dictionary. The dictionary contains more than 13,000 common words, phrases, and other substrings from a large corpus of text and HTML documents. Predefined algorithms can increase the compression density of smaller files.

Excerpt from:
https://segmentfault.com/a/1190000009383543

  • MimeTypes: Set the MimeTypes to be compressed
  • GzipCompressionProviderOptions: Set the compression mode (the default is CompressionLevel.Fastest fast compression)
Before compression:
After compression:

The advantage of using compression is to save network traffic and compress resource files. But it consumes a little CPU performance.

gzip

  • By default, the Brotli compression provider is added to the array of compression providers along with the Gzip compression provider.
  • He defaults to Brotil compression. If the client does not support Brotli and the client supports Gzip, the default is Gzip.
Copy   public void ConfigureServices(IServiceCollection services)
        {
           services.AddResponseCompression(options=> {
               options.Providers.Add<BrotliCompressionProvider>();
               options.Providers.Add<GzipCompressionProvider>();

           });
            services.AddRazorPages();
        }

Some MIME types require us to add them to the compression type for ourselves. We can see from the figure that there are some uncompressed at the moment, then we can manually add them to the type.

Copy    public void ConfigureServices(IServiceCollection services)
        {
           services.AddResponseCompression(options=> {
               options.Providers.Add<BrotliCompressionProvider>();
               options.Providers.Add<GzipCompressionProvider>();

               options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "image/x-icon" });

           });
            services.AddRazorPages();
        }

How to configure the compression level





Compression level
description




CompressionLevel.Fastest
Compression should be done as soon as possible, even if the resulting output is not compressed optimally.


CompressionLevel.NoCompression
Compression should not be performed.


CompressionLevel.Optimal
Even if compression takes longer, the response should be compressed optimally.


Copy
public void ConfigureServices(IServiceCollection services)
{
        services.AddResponseCompression();
        
            services.Configure<GzipCompressionProviderOptions>(options => 
                {
                        options.Level = CompressionLevel.Fastest;
                            });
                            })
}

Security protocol compression

You can use the EnableForHttps option to control the compression response on a secure connection, which is disabled by default. Using compression on dynamically generated pages can lead to security issues such as CRIME and BREACH attacks.

  • EnableForHttps: Whether to compress HTTPS packets (default is false)
Copy        public void ConfigureServices(IServiceCollection services)
        {
           services.AddResponseCompression(options=> {
               options.Providers.Add<BrotliCompressionProvider>();
               options.Providers.Add<GzipCompressionProvider>();
               options.EnableForHttps = true;
               options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "image/x-icon" });

           });
            services.AddRazorPages();
        }

Interested partners in the dotnet Jinan club can join the QQ group: 743523033

Orignal link:https://www.cnblogs.com/yyfh/p/11796421.html