Skip to content

Instantly share code, notes, and snippets.

@rossmerr
Created January 27, 2016 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossmerr/bb9163703370b4059733 to your computer and use it in GitHub Desktop.
Save rossmerr/bb9163703370b4059733 to your computer and use it in GitHub Desktop.
A gzip, deflate compression middleware for vNext, ASP.NET Core
public class CompressionMiddleware
{
private readonly RequestDelegate _next;
public CompressionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (IsGZipSupported(context))
{
string acceptEncoding = context.Request.Headers["Accept-Encoding"];
var buffer = new MemoryStream();
var stream = context.Response.Body;
context.Response.Body = buffer;
await _next(context);
if (acceptEncoding.Contains("gzip"))
{
var gstream = new GZipStream(stream, CompressionLevel.Optimal);
context.Response.Headers.Add("Content-Encoding", new[] {"gzip"});
buffer.Seek(0, SeekOrigin.Begin);
await buffer.CopyToAsync(gstream);
gstream.Dispose();
}
else
{
var gstream = new DeflateStream(stream, CompressionLevel.Optimal);
context.Response.Headers.Add("Content-Encoding", new[] { "deflate" });
buffer.Seek(0, SeekOrigin.Begin);
await buffer.CopyToAsync(gstream);
gstream.Dispose();
}
}
else
{
await _next(context);
}
}
public bool IsGZipSupported(HttpContext context)
{
string acceptEncoding = context.Request.Headers["Accept-Encoding"];
return !string.IsNullOrEmpty(acceptEncoding) &&
(acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate"));
}
}
@rossmerr
Copy link
Author

add app.UseMiddleware<CompressionMiddleware>(); to your request pipeline within the Configure method in your Startup.cs

@matthewdaniel
Copy link

this (along with other copy pasta implementations) only works on the first request. All other requests have content length of 0. Any idea?

@rossmerr
Copy link
Author

rossmerr commented Nov 2, 2016

@matthewdaniel if you send me a sample solution or unit test I'll take a look

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment