Response Compression in a .Net Core API

hisudip_

Sudip

Posted on June 16, 2023

Response Compression in a .Net Core API

By enabling response compression, you can reduce the size of the responses sent by your API, improving network efficiency and overall performance.

Install the package Microsoft.AspNetCore.ResponseCompression

Configure it as shown in the code snippet.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using System.IO.Compression;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCompression(options =>
        {
            options.EnableForHttps = true; // Enable compression for HTTPS requests
            options.Providers.Add<BrotliCompressionProvider>(); // Use Brotli compression
            options.Providers.Add<GzipCompressionProvider>(); // Use Gzip compression
        });

        services.Configure<BrotliCompressionProviderOptions>(options =>
        {
            options.Level = CompressionLevel.Fastest; // Set the compression level for Brotli
        });

        services.Configure<GzipCompressionProviderOptions>(options =>
        {
            options.Level = CompressionLevel.Optimal; // Set the compression level for Gzip
        });

        // Other service configurations...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Other app configurations...

        app.UseResponseCompression();

        // Other app middleware...
    }
}
Enter fullscreen mode Exit fullscreen mode

Thank you.
Please follow me for more articles.

💖 💪 🙅 🚩
hisudip_
Sudip

Posted on June 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related