Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Action Filter for Compression

0.00/5 (No votes)
17 Apr 2014 1  
This tip will help to create an action filter to compress the contents like Json, partial view, etc.

Introduction

This tip will help to create an action filter to compress the contents like Json, partial view, etc.

Using the Code

Step 1: Create a class which will be derived from ActionFilterAttribute.

Step 2: Overwrite the method OnActionExecuting.

 public class CompressAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;
 
            string Encodingtype = request.Headers["Accept-Encoding"];
 
            if (string.IsNullOrEmpty(Encodingtype)) return;
 
            Encodingtype = Encodingtype.ToUpperInvariant();
 
            HttpResponseBase responseMessage = filterContext.HttpContext.Response;
 
            if (Encodingtype.Contains("GZIP"))
            {
                responseMessage.AppendHeader("Content-encoding", "gzip");
                responseMessage.Filter = new GZipStream(responseMessage.Filter, CompressionMode.Compress);
            }
            else if (Encodingtype.Contains("DEFLATE"))
            {
                responseMessage.AppendHeader("Content-encoding", "deflate");
                responseMessage.Filter = new DeflateStream(responseMessage.Filter, CompressionMode.Compress);
            }
        }
    }  

Step 3: In this method, check the request header if it contains the gzip or deflate encoding. If yes, then add the response with the compression filter.

Step 4: Use the attribute on top of action of a controller.

  [Compress]
        public ActionResult ShowMeritUsageResults(FormCollection model)
        {
  // test code....
        }  

Points of Interest

Install the fiddler, and see the difference between the size before and after compression. Please find the code here.

History

  • 17th April, 2014: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here