I’d previously created a compression processor for dynamic content – using this excellent post for QValues by Dave Transom. Also just just discovered this post on creating an action filter for compression by Kazi Manzur Rashid.
So combining the two and we have:
public class CompressFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpRequestBase request = filterContext.HttpContext.Request; // load encodings from header QValueList encodings = new QValueList(request.Headers["Accept-Encoding"]); // get the types we can handle, can be accepted and in the defined client preference QValue preferred = encodings.FindPreferred("gzip", "deflate", "identity"); // if none of the preferred values were found, but the // client can accept wildcard encodings, we'll default // to Gzip. if (preferred.IsEmpty && encodings.AcceptWildcard && encodings.Find("gzip").IsEmpty) preferred = new QValue("gzip"); HttpResponseBase response = filterContext.HttpContext.Response; // handle the preferred encoding switch (preferred.Name) { case "gzip": response.AppendHeader("Content-encoding", "gzip"); response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); break; case "deflate": response.AppendHeader("Content-encoding", "deflate"); response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); break; case "identity": break; default: break; } } }
Which when applied as below to any action method will enable compression if it’s supported by the browser.
[AcceptVerbs(HttpVerbs.Get)] [CompressFilter] public ContentResult SiteMap() { return new ContentResult { Content = SyndicationHelper.GetAggregateSiteMap(), ContentType = "application/xml; charset=UTF-8" }; }
Download here: QValueAndCompressionFilter.zip
7 Comments
Add new comment