Search code examples
c#asp.net-core

How to compress the HTTP response of a custom middleware?


When using the following code and running it in Visual Studio, the response is not being compressed. When I comment out the UseMiddleware and uncomment the MapGet, the compression works fine.

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression();

WebApplication app = builder.Build();

app.UseHttpsRedirection();
app.UseResponseCompression();

// Use middleware -> no compression
app.UseMiddleware<MyMiddleware>();
// MapGet instead of middleware -> have compression
//app.MapGet("/", () => "Hello World!");

app.Run();

public class MyMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.StatusCode = 200;
        await context.Response.WriteAsync(String.Join(",",Enumerable.Range(0,1000).Select(i=>$"{i}")));
        await next(context);
    }
}

Solution

  • The response compression middleware will only compress a set number of content types (docs). The default content types can be found in the source repository. So if you set the content type to "text/plain" in your middleware this works as you expect.

    public class MyMiddleware(RequestDelegate next)
    {
        public async Task InvokeAsync(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.StatusCode = 200;
            await context.Response.WriteAsync(String.Join(",",Enumerable.Range(0,1000).Select(i=>$"{i}")));
            await next(context);
        }
    }