1

We are trying to implement response compression in ASP.NET Core 6 Web API. We are using, Microsoft.AspNetCore.ResponseCompression -Version 2.2.0. And here is the code/structure to implement this API:

Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddResponseCompression(options =>
{ 
    options.MimeTypes =
            ResponseCompressionDefaults.MimeTypes.Concat(
                new[]
                {
                    "application/javascript",
                    "application/json",
                    "application/xml",
                    "text/css",
                    "text/html",
                    "text/json",
                    "text/plain",
                    "text/xml"
                });

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

builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Fastest;
});

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

var app = builder.Build();
app.UseResponseCompression();

This is the sample API:

[Produces("application/json")]
public class ResponseCompressionController: ControllerBase
{
    [HttpGet]
    public List<Post> Get()
    {
         List<Post> lstPost = new List<Post>();
            
         for (int count = 0; count < 1000; count++)
         {
             Post post = new Post();
             post.Text = "Adding new post with number" + "_" + count;
             lstPost.Add(post);
         }

         return lstPost;
     }
}

However, after doing this, we are not able to see the difference whether the API is sending/compressing the response. Even when we try to keep compression OR not, the response size is same.

We have tried this for other API's but the there is no difference in the response.

Is anything more need to be done?

Any help on this appreciated.

EDIT 1: I have created a new project and kept minimal code, still I am not getting the expected response.

Program.cs

using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddResponseCompression(options =>
{
    options.MimeTypes =
        ResponseCompressionDefaults.MimeTypes.Concat(
            new[]
            {
                "application/javascript",
                "application/json;",
                "application/xml",
                "text/css",
                "text/html",
                "text/json",
                "text/plain",
                "text/xml"
            });

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

builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Fastest;
});

builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseResponseCompression();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

And in controller

using Microsoft.AspNetCore.Mvc;

namespace responsecompression.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

Interestingly, after applying compression, response size is getting increased.

Before compression Before compression

After Compression enter image description here

XamDev
  • 3,377
  • 12
  • 58
  • 97
  • If you change the GzipCompressionProviderOptions Level to SmallestSize do you see it do anything? Chances are at Optimal its not really finding a need to compress anything. Also, when you call that API on the Response headers do you see the content as "application/json" ? – Melroy Coelho Jun 26 '23 at 18:32
  • 1
    `Microsoft.AspNetCore.ResponseCompression` is legacy package for ASP.NET Core 2.x versions, remove it. Response compression is shipped by default with ASP.NET Core in later versions. – Guru Stron Jun 26 '23 at 18:46
  • Was not able to repro. For me a see clear difference between response sizes when commenting in/out the `app.UseResponseCompression();`. – Guru Stron Jun 26 '23 at 18:51
  • @GuruStron So, is that I am using version 2.x and not the default in which comes with asp.net core. Also, I have given the necessary part of the Program.cs and not the whole. – XamDev Jun 26 '23 at 18:54
  • @GuruStron Also, do I need to pass content-encoding in response explicitly. If you can share the code snippet that would be good. – XamDev Jun 26 '23 at 18:58
  • 1
    @XamDev yes, sure - [@github](https://github.com/gurustron/playground/tree/master/csharp/SOAnswers/NET6/WebApplicationCaching). Note that I was testing with http, not https. Commenting in/out the `app.UseResponseCompression();` (with restart) resulted in `http://localhost:5143/WeatherForecast` returning either ~370 B or ~550 B. – Guru Stron Jun 26 '23 at 19:17
  • @GuruStron Thanks for the quick help. I will play with it and let you know the findings – XamDev Jun 26 '23 at 19:39
  • @GuruStron I have tried the way you have provided. But I am not getting compressed response size still. Even created a new project instead of adding in existing project. Any help on this appreciated. – XamDev Jun 28 '23 at 16:45
  • 1
    @XamDev try using Fiddler or Chrome developer tools to check the size. – Guru Stron Jun 28 '23 at 17:18

1 Answers1

1

It seems that Postman is showing the decompressed size not the transferred one, so it is not the ASP.NET Core not working but the observer tool:

Response compression enabled:

Chrome dev tools:

enter image description here

Postman:

enter image description here

Response compression disabled:

Chrome dev tools:

enter image description here

Postman:

enter image description here

Also see:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132