8

I want to compress my web application with Gzip and I am using following class

compression filter

public class CompressFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext 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;
        if (acceptEncoding.Contains("GZIP"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
        else if (acceptEncoding.Contains("DEFLATE"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
    }
}

cache filter

public class CacheFilterAttribute : ActionFilterAttribute
{
    public int Duration
    {
        get;
        set;
    }

    public CacheFilterAttribute()
    {
        Duration = 1;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (Duration <= 0) return;

        HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
        TimeSpan cacheDuration = TimeSpan.FromMinutes(Duration);

        cache.SetCacheability(HttpCacheability.Public);
        cache.SetExpires(DateTime.Now.Add(cacheDuration));
        cache.SetMaxAge(cacheDuration);
        cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
    }
}

controller

[CompressFilter]
[CacheFilter(Duration = 60)]
public ActionResult Index()
{}

and applying this class to Action in Controller. But in firebug it's still showing "Transfer-Encoding: chunked" , but it should be "Transfer-Encoding: gzip".

I am testing it on localhost.

Please tell me what am I doing wrong? Thanks and Regards.

update cache filter is working fine, but still no gzip compression, below is response header in chrome.

Cache-Control:public, must-revalidate, proxy-revalidate, max-age=3600
Content-Type:text/html; charset=utf-8
Date:Wed, 22 Jul 2015 13:39:06 GMT
Expires:Wed, 22 Jul 2015 14:39:04 GMT
Server:Microsoft-IIS/10.0
Transfer-Encoding:chunked
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:5.1
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcQXJiYXpcRG9jdW1lbnRzXFZpc3VhbCBTdHVkaW8gMjAxM1xQcm9qZWN0c1xidXlwcmljZXNwYWtpc3RhblxCdXlQaG9uZQ==?=

Is there any way I can make this work, I really need help guys, Thanks

aadi1295
  • 982
  • 3
  • 19
  • 47
  • can anyone help? I really need to fix this.. searching for couple of days but still unable to compress. Thanks – aadi1295 Jul 21 '15 at 21:25

2 Answers2

15

If you can't control IIS, just add this to your Global.ASCX. tested on Android, iPhone, and most PC browsers.

 protected void Application_BeginRequest(object sender, EventArgs e)
    {

        // Implement HTTP compression
        HttpApplication app = (HttpApplication)sender;


        // Retrieve accepted encodings
        string encodings = app.Request.Headers.Get("Accept-Encoding");
        if (encodings != null)
        {
            // Check the browser accepts deflate or gzip (deflate takes preference)
            encodings = encodings.ToLower();
            if (encodings.Contains("deflate"))
            {
                app.Response.Filter = new DeflateStream(app.Response.Filter, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "deflate");
            }
            else if (encodings.Contains("gzip"))
            {
                app.Response.Filter = new GZipStream(app.Response.Filter, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "gzip");
            }
        }
    }
Ian Vink
  • 66,960
  • 104
  • 341
  • 555
  • 1
    Red flag! This answer caused a severe problem for us. You should be using `Application_PostReleaseRequestState`. As per this article https://docs.microsoft.com/en-us/previous-versions/ms178473(v=vs.140) 18. Raise the PostReleaseRequestState event. 19. Perform response filtering if the Filter property is defined. The problem we were having is that on Exception, our Exception handler was rewriting the headers. I think we had other issues, too, but certainly anywhere you rewrite the headers, the content would be deflated but the headers wouldn't tell the browser that, and you'd get garbage. – Bluebaron Feb 23 '19 at 00:37
  • Also, your answer should consider the order of the requested compression method provided by the client. – Bluebaron Feb 23 '19 at 00:52
1

Check your local IIS if Compression is properly configured. Please refer the following link to properly configure IIS for HTTP Compression.

http://www.iis.net/configreference/system.webserver/httpcompression

Adersh M
  • 596
  • 3
  • 19
  • Yes it's fully configured. I have also checked with deploying the site in IIS 8.5 in Windows 8.1 (no IIS express) but still showing "Transfer-Encoding: chunked" in firebug. any suggestion? – aadi1295 Jul 21 '15 at 10:49
  • Have you debugged CompressFilter? Put a breakpoint in CompressFilter and check if headers are properly appended to response. – Adersh M Jul 21 '15 at 11:19
  • @Ardersh: Thanks for your response, I have checked the header value by putting a break point and it is `{Server=Microsoft-IIS%2f8.0&X-AspNetMvc-Version=5.1&Content-encoding=gzip}` Its trying to add `Content-encoding=gzip` but not showing in firebug. – aadi1295 Jul 21 '15 at 11:56
  • While checking for the issue, I found the solution in http://stackoverflow.com/questions/11435200/why-does-my-c-sharp-gzip-produce-a-larger-file-than-fiddler-or-php/11435898#11435898 – Adersh M Jul 21 '15 at 12:37
  • @Ardersh: Thanks again, I have tried to solve this issue by using DotNetZip and still nothing changed in the header. This is so annoying. Can you please suggest something else. Thanks – aadi1295 Jul 21 '15 at 14:34
  • Have you tried the same in chrome? because, from Bugzilla@Mozilla(https://bugzilla.mozilla.org/show_bug.cgi?id=68517) link i read that there is a problem with gzip encoding in Firefox browsers. – Adersh M Jul 22 '15 at 04:04