Request decompression of content in ASP.Net Core

I sometimes have to post great useful JSON requests for my main ASP.Net controllers. The size of the payload order (at least in my opinion) compresses it. Since the main ASP.Net controllers do not seem to support compressed content request out of the box, I deployed my own middleware.

The implementation of this was so trivial that I’m not sure that something is missing here. Either because there is a built-in way to achieve this, or because I made some serious mistake in terms of security or performance?

public class GzipRequestContentEncodingMiddleware { public GzipRequestContentEncodingMiddleware(RequestDelegate next) { if (next == null) throw new ArgumentNullException(nameof(next)); this.next = next; } private readonly RequestDelegate next; private const string ContentEncodingHeader = "Content-Encoding"; private const string ContentEncodingGzip = "gzip"; private const string ContentEncodingDeflate = "deflate"; public async Task Invoke(HttpContext context) { if (context.Request.Headers.Keys.Contains(ContentEncodingHeader) && (context.Request.Headers[ContentEncodingHeader] == ContentEncodingGzip || context.Request.Headers[ContentEncodingHeader] == ContentEncodingDeflate)) { var contentEncoding = context.Request.Headers[ContentEncodingHeader]; context.Request.Headers.Remove(ContentEncodingHeader); var destination = new MemoryStream(); using (var decompressor = contentEncoding == ContentEncodingGzip ? (Stream) new GZipStream(context.Request.Body, CompressionMode.Decompress, true) : (Stream) new DeflateStream(context.Request.Body, CompressionMode.Decompress, true)) { await decompressor.CopyToAsync(destination); } destination.Seek(0, SeekOrigin.Begin); context.Request.Body = destination; context.Request.Headers["Content-Length"] = destination.Length.ToString(CultureInfo.InvariantCulture); } await next(context); } } 
+23
c # asp.net-core compression decompression asp.net-core-middleware
source share
2 answers

I know this is a pretty old post, but just in case, if it helps someone, here is the nuget package to execute the decompression request in the .net kernel

https://github.com/alexanderkozlenko/aspnetcore-request-decompression

+3
source share

Response Compression middleware and services are provided offline in ASPNETCORE.

You can use the nuget package Microsoft.AspNetCore.ResponseCompression by following the instructions in the official ASPNETCORE docs .

-3
source share

All Articles