Skip to content

Instantly share code, notes, and snippets.

@bjartwolf
Last active August 29, 2015 14:27
Show Gist options
  • Save bjartwolf/68cb8f27f889023a9460 to your computer and use it in GitHub Desktop.
Save bjartwolf/68cb8f27f889023a9460 to your computer and use it in GitHub Desktop.
gzipstream
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