Compress the Response Content in ASP.NET MVC
performance of their ASP.NET MVC application. In addition to minifying
HTML response. You may minify the HTML output from a view or you may compress
the output (you can also use both together). To that end this article shows how
to compress HTML response by writing a custom action filter.
To compress the response you can use classes from System.IO.Compression
namespace. Especially GZipStream and DeflateStream classes come handy when it
comes to compressing the response. So, let's write a simple custom action filter
that does this job.
public class GZipOrDeflateAttribute:ActionFilterAttribute
public override void OnActionExecuting
string acceptencoding = filterContext.HttpContext.
acceptencoding = acceptencoding.ToLower();
var response = filterContext.HttpContext.Response;
response.Filter = new GZipStream(response.Filter,
else if (acceptencoding.Contains("deflate"))
response.Filter = new DeflateStream(response.Filter,
The above code creates GZipOrDeflateAttribute class that inherits from
ActionFilterAttribute base class. It then overrides OnActionExecuting() method
of the base class.
Inside, we retrieve the value of Accept-Encoding HTTP header. This header is
sent by the browser along with the request. This header indicates the encoding
types that the browser can understand. For example, on Chrome this header is
We then check the value of this header. If Accept-Encoding contains gzip it
indicates that GZip compression is supported. We then append Content-Encoding
HTTP header to the response and set its value to gzip. The Filter property of
the Response is set to an instance of GZipStream class. Notice that while
creating the GZipStream object we pass the original filter stream and
compression mode of Compress to its constructor.
If gzip is not supported then we check whether deflate is supported.
Accordingly we set Content-Encoding to deflate and create an object of
DeflateStream class to assign to the Filter property.
Once the GZipOrDeflateAttribute class is ready you can use it as shown below:
public ActionResult Index()
using (NorthwindEntities db = new NorthwindEntities())
To check the response content size before and after the compression you can
use browser's developer tools. For example, the following figure shows that the
response content length for a test view without any compression.
The same application after enabling compression using [GZipOrDeflate]
attribute returns this:
As you can see there is reduction in the size of the response content.
If you wish to apply minification to your HTML response then you may also
have a look at these NuGet packages -
That's it! Keep coding!!