Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GZipping content files in ASP.NET MVC 3

I use the following attribute to decorate my BaseController class.

public class OutputCompressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(encodingsAccepted))
            return;

        encodingsAccepted = encodingsAccepted.ToLowerInvariant();
        HttpResponseBase response = filterContext.HttpContext.Response;

        if (encodingsAccepted.Contains("gzip"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
        else if (encodingsAccepted.Contains("deflate"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
    }
}

The issue is that, even though this works just fine for views and every action result, the attribute isn't working for stuff on the /Content folder of the project. I was wondering how I could make it so that files in the Content folder use a controller, or are bound somehow or hooked by something that allows me to append these filters to the response header.

like image 880
bevacqua Avatar asked Jan 18 '23 12:01

bevacqua


1 Answers

Instead of writing such action filters and reinventing the wheels you could activate compression in IIS. You could do this for static and dynamic content.

like image 123
Darin Dimitrov Avatar answered Jan 20 '23 03:01

Darin Dimitrov