When we are using a web application, the application transmits large amount of data content between server and client via http responds.
We can reduce to some amount of data content http respond data content length using MVC controller action filter attributes. This helps a lot in web applications to improve performance.
Description with the Code
The following compress filter class inherited from
ActionFilterAttribute class represents the "
ActionFilter" for compressing any data content send server to client side in web application through http respond like AJAX in IIS server. This is a custom
ActionFilter attribute class and you can write in filters folder in MVC web project.
public class CompressFilter : ActionFilterAttribute
public override void OnActionExecuting(FilterExecutingContext filterContext)
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
else if (acceptEncoding.Contains("DEFLATE"))
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
Now, we can use
compressFilter attribute bottom of any action in any controller class like the following code snippet.
public ActionResult Index()
And we can use filter attributes in any Ajax call action in controller class.
public ActionResult FilterRegions(string countryId)
Run your application and analysis when your respond is compressed and not. You can feel how much data content is compressed with this method.
Note: When you compress the content whose content length is less than 1000, this method would not be successful, because that takes more time to compress than to send that amount of content.
You can see http content length through Firefox FireBug or Chrome Dev tool.
Normally GZIP compression is allowed by any browser today, even Internet Explorer.
Points of Interest
This method is very easy and successful to compress data content transmission via http request in web application.