Introduction
GZIP compression can help to our website to reduce its bandwidth usage. In this article, we can incorporate GZIP feature in our MVC app. We can enable GZIP header through our website, alternatively we can also enable GZIP through our website IIS. Here describing, how to use GZIP compression in our ASP.net MVC app.Already Discussed on ASP.Net MVC Security & Performance
- How to Prevent Direct URL Access In MVC
- Asp.net MVC session management example
- Prevent Cross-Site Request Forgery using AntiForgeryToken() in MVC
Main benefits of GZIP compression are under below:
- It helps to reduce sizes of our website pages.
- It helps to increase speed of web pages.
- It mounts to cost-benefit ratio high.
Namespace:
We need to add two namespaces before to write code of GZIP compression.using System.Web.Mvc; using System.IO.Compression;
Code of GZIP Compress under FilterConfig.cs
Write this code under FilterConfig.cs in App_Start folder of your MVC App.public class CompressAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var _encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(_encodingsAccepted)) return; _encodingsAccepted = _encodingsAccepted.ToLowerInvariant(); var _response = filterContext.HttpContext.Response; if (_encodingsAccepted.Contains("deflate")) { _response.AppendHeader("Content-encoding", "deflate"); _response.Filter = new DeflateStream(_response.Filter, CompressionMode.Compress); } else if (_encodingsAccepted.Contains("gzip")) { _response.AppendHeader("Content-encoding", "gzip"); _response.Filter = new GZipStream(_response.Filter, CompressionMode.Compress); } } }
Call Compress Attribute in MVC Controller
Now call Compress attribute on your controller action to get done this functionality in your MVC application.Working Sample:
Here, I am showing statistics of my web page difference between zipped and unzipped webpage.Unzip Webpage:
Unzip Webpage |
Requests | 34 |
Size | 124 KB |
Finish | 5.33s |
DOContentLoaded | 617 ms |
Load | 689 ms |
Gzip Webpage:
Gzip Webpage |
Requests | 34 |
Size | 123 KB |
Finish | 1.36s |
DOContentLoaded | 523 ms |
Load | 582 ms |
Finally, you can find difference between unzip and zip web pages. It is very required that your web pages should be Gzip enabled through IIS or visual studio project so that it will increase performance of your web pages in web browser (Chrome, IE, FF, Opera etc.). Here, I have explained how to use GZIP compression in ASP.net MVC app.
[Compress] public ActionResult Index() { /// write here your logic to pull data from database return View(); }
Fitercontext is showing null..
ReplyDeletecan you more specify your problem?
ReplyDeleteit only works for HTML what to do CSS and Javascript?
ReplyDeleteit only works for HTML what to do CSS and Javascript?
ReplyDeletethere there are so many tools online to gzip online.
Delete