Created
January 27, 2016 17:36
-
-
Save rossmerr/bb9163703370b4059733 to your computer and use it in GitHub Desktop.
A gzip, deflate compression middleware for vNext, ASP.NET Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
} | |
} |
this (along with other copy pasta implementations) only works on the first request. All other requests have content length of 0. Any idea?
@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
add
app.UseMiddleware<CompressionMiddleware>();
to your request pipeline within the Configure method in your Startup.cs