Advanced - Request decompression

In this article

Request decompression middleware:

When the Content-Encoding header value on a request matches one of the available decompression providers, the middleware:

Requests that don't include a Content-Encoding header are ignored by the request decompression middleware.

Decompression:

If the middleware encounters a request with compressed content but is unable to decompress it, the request is passed to the next delegate in the pipeline. For example, a request with an unsupported Content-Encoding header value or multiple Content-Encoding header values is passed to the next delegate in the pipeline.

Configuration

The following code uses AddRequestDecompression(IServiceCollection) and UseRequestDecompression to enable request decompression for the default Content-Encoding types:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRequestDecompression();

var app = builder.Build();

app.UseRequestDecompression();

app.MapPost("/", (HttpRequest request) => Results.Stream(request.Body));

app.Run();

Default decompression providers

The Content-Encoding header values that the request decompression middleware supports by default are listed in the following table:

Content-Encoding header values Description
br Brotli compressed data format
deflate DEFLATE compressed data format
gzip Gzip file format

Custom decompression providers

Support for custom encodings can be added by creating custom decompression provider classes that implement IDecompressionProvider:

public class CustomDecompressionProvider : IDecompressionProvider
{
    public Stream GetDecompressionStream(Stream stream)
    {
        // Perform custom decompression logic here
        return stream;
    }
}

Custom decompression providers are registered with RequestDecompressionOptions along with their corresponding Content-Encoding header values:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRequestDecompression(options =>
{
    options.DecompressionProviders.Add("custom", new CustomDecompressionProvider());
});

var app = builder.Build();

app.UseRequestDecompression();

app.MapPost("/", (HttpRequest request) => Results.Stream(request.Body));

app.Run();

Request size limits

In order to guard against zip bombs or decompression bombs:

In order of precedence, the maximum request size for an endpoint is set by:

Web server implementation MaxRequestBodySize configuration
HTTP.sys HttpSysOptions.MaxRequestBodySize
IIS IISServerOptions.MaxRequestBodySize
Kestrel KestrelServerLimits.MaxRequestBodySize

Warning Disabling the request body size limit poses a security risk in regards to uncontrolled resource consumption, particularly if the request body is being buffered. Ensure that safeguards are in place to mitigate the risk of denial-of-service (DoS) attacks.

Additional Resources

Ref: Request decompression in ASP.NET Core