Tuesday, 4 February 2014

Enable gzip compression ASP.Net MVC



1.  You can configure compression through your web.config file as follows:
<system.webServer>
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
</system.webServer>

2.  You could also do this in code if you rather do that. I would make a basecontroller which every control inherits from and decorate it with this attribute below.
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);
        }
    }
}

No comments:

Post a Comment