Sunday, February 15, 2015

Enabling GZip Compression in WebAPI and Owin

Interesting little challenge today. I’m building an application that uses Web API and will run in an OWIN SelfHost and my payload as big enough to warrant GZip Compression. But, since my app is running as an Owin Selfhosted api, I can’t use IIS Compression.

So I created a little compression attribute. Seems to work great.

   1: namespace eVision.AppShaping.Handlers.Controllers
   2: {
   3:     using System.IO.Compression;
   4:     using System.Linq;
   5:     using System.Net.Http;
   6:     using System.Threading;
   7:     using System.Threading.Tasks;
   8:     using System.Web.Http.Filters;
   9:  
  10:     internal class GzipCompressedAttribute : System.Web.Http.Filters.ActionFilterAttribute
  11:     {
  12:         public override async Task OnActionExecutedAsync(HttpActionExecutedContext actContext, CancellationToken token)
  13:         {
  14:             bool supportGZip = actContext.Request.Headers.AcceptEncoding.Any(x => x.Value == "gzip");
  15:  
  16:             if (!supportGZip)
  17:             {
  18:                 await base.OnActionExecutedAsync(actContext, token);
  19:                 return;
  20:             }
  21:  
  22:             var contentStream = await actContext.Response.Content.ReadAsStreamAsync();
  23:  
  24:             actContext.Response.Content = new PushStreamContent(async (stream, content, context) =>
  25:             {
  26:                 using(contentStream)
  27:                 using (var zipStream = new GZipStream(stream, CompressionLevel.Optimal))
  28:                 {
  29:                     await contentStream.CopyToAsync(zipStream);
  30:                 }
  31:             });
  32:  
  33:             actContext.Response.Content.Headers.Remove("Content-Type");
  34:             actContext.Response.Content.Headers.Add("Content-encoding", "gzip");
  35:             actContext.Response.Content.Headers.Add("Content-Type", "application/json");
  36:         }
  37:     }
  38: }

5 comments:

  1. Replies
    1. here is another example, http://blog.developers.ba/asp-net-web-api-gzip-compression-actionfilter/ regards

      Delete
  2. This is open source: https://github.com/Thorium/Owin.Compression

    ReplyDelete