Gzip compression not working ASP.net MVC5
Asked Answered
D

2

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

Derosier answered 21/7, 2015 at 1:50 Comment(1)
can anyone help? I really need to fix this.. searching for couple of days but still unable to compress. ThanksDerosier
B
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");
            }
        }
    }
Bloomers answered 28/3, 2016 at 1:16 Comment(2)
Red flag! This answer caused a severe problem for us. You should be using Application_PostReleaseRequestState. As per this article 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.Ephemeron
Also, your answer should consider the order of the requested compression method provided by the client.Ephemeron
T
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

Twelvetone answered 21/7, 2015 at 4:28 Comment(6)
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?Derosier
Have you debugged CompressFilter? Put a breakpoint in CompressFilter and check if headers are properly appended to response.Twelvetone
@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.Derosier
While checking for the issue, I found the solution in #11435700Twelvetone
@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. ThanksDerosier
Have you tried the same in chrome? because, from Bugzilla@Mozilla(bugzilla.mozilla.org/show_bug.cgi?id=68517) link i read that there is a problem with gzip encoding in Firefox browsers.Twelvetone

© 2022 - 2024 — McMap. All rights reserved.