title: Compression filter for Web API
body: <p>I've been using the compression filter for my MVC actions as detailed here:</p>
  
  <p><a href="http://msdn.microsoft.com/en-us/magazine/gg232768.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/magazine/gg232768.aspx</a></p>
  
  <p>I've tried to re-purpose the code to do something similar for Web API, but I've hit a roadblock:</p>
  
  <pre><code>public class CompressAPIAttribute : System.Web.Http.Filters.ActionFilterAttribute
  {
      public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
      {
          var preferredEncoding = GetPreferredEncoding(filterContext.Request);
          Stream compressedStream = null;
          // Compress the response accordingly
          var response = filterContext.Response;
          response.Headers.Add("Content-encoding", preferredEncoding.ToString());
  
          if (preferredEncoding == CompressionScheme.Gzip)
          {
              response.Content = new GZipStream(compressedStream, CompressionMode.Compress); //THIS WON'T WORK
          } 
  
          if (preferredEncoding == CompressionScheme.Deflate)
          {
              response.Content = new DeflateStream(compressedStream, CompressionMode.Compress); //THIS WON'T WORK
          }
          return;
      }
  
      enum CompressionScheme
      {
          Gzip = 0,
          Deflate = 1,
          Identity = 2
      }
  
      private CompressionScheme GetPreferredEncoding(HttpRequestMessage request)
      {
          var acceptableEncoding = request.Headers.AcceptEncoding;
  
          if (acceptableEncoding.Where(h =&gt; h.Value.Contains("gzip")).Count() &gt; 0)
              return CompressionScheme.Gzip;
  
          if (acceptableEncoding.Where(h =&gt; h.Value.Contains("deflate")).Count() &gt; 0)
              return CompressionScheme.Deflate;
  
          return CompressionScheme.Identity;
      }
  </code></pre>
  
  <p>Any ideas how I can assign a compressed stream to the response's content?</p>
  
  <p>I should point out this is being hosted in IIS 6.0, which I do not control.</p>