DEV Community

Cover image for Response Compression in a .Net Core API
Sudip
Sudip

Posted on

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.

Top comments (0)