In the previous article, We've seen how to enable response compression, and in this article we're going to see how to accept requests that have compressed content.

ASP.NET Core doesn't provide any built-in classes to support this scenario, but fortunately it's flexible enough to add this behavior in a few lines.

The idea is to decompress the body of requests that have as head Content encoding with values gzip, decay or br.


    public class CompressionMiddleware
    {
        private readonly RequestDelegate _next;

        public CompressionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // Récupération de l'entête Content-Encoding.
            var content = context.Request.Headers["Content-Encoding"];
            if (!string.IsNullOrWhiteSpace(content) && context.Request.Body != null)
            {
                if (content.Contains("gzip"))
                {
                    // On remplace le stream par un stream Gzip
                    context.Request.Body = new GZipStream(context.Request.Body, CompressionMode.Decompress);
                }
                else if (content.Contains("br"))
                {
                    // On remplace le stream par un stream Brotli
                    context.Request.Body = new BrotliStream(context.Request.Body, CompressionMode.Decompress);
                }
                else if (content.Contains("deflate"))
                {
                    // On remplace le stream par un stream deflate
                    context.Request.Body = new DeflateStream(context.Request.Body, CompressionMode.Decompress);
                }
            }

            await _next(context);
        }
    }

Once the middleware is defined, it must be added to the method Configuring of the class Start-up


            app.UseMiddleware<CompressionMiddleware>();

Happy coding !