Last active
August 29, 2015 14:27
-
-
Save bjartwolf/68cb8f27f889023a9460 to your computer and use it in GitHub Desktop.
gzipstream
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.IO.Compression; | |
using System.Threading.Tasks; | |
using Microsoft.Owin; | |
namespace ZipMiddleware | |
{ | |
using AppFunc = Func<IDictionary<string, object>, Task>; | |
public class GzipMiddleware | |
{ | |
private readonly AppFunc _next; | |
public GzipMiddleware(AppFunc next) | |
{ | |
this._next = next; | |
} | |
public async Task Invoke(IDictionary<string, object> env) | |
{ | |
var ctx = new OwinContext(env); | |
var encodingHeaders = ctx.Request.Headers.GetCommaSeparatedValues("Accept-Encoding"); | |
var acceptGzip = encodingHeaders != null && encodingHeaders.Contains("gzip"); | |
if (acceptGzip) | |
{ | |
ctx.Response.Body = new BufferedStream(new GZipStream(ctx.Response.Body,CompressionLevel.Fastest)); | |
ctx.Response.OnSendingHeaders(state => | |
{ | |
var resp = (OwinResponse)state; | |
resp.Headers.Set("Content-Encoding", "gzip"); | |
resp.Headers.Add("Transfer-Encoding",new[] {"chunked"}); | |
}, ctx.Response); | |
} | |
await _next(env); | |
ctx.Response.Body.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment