Need help with GZIP Compression

Discussion in 'C#' started by akshaykalia, Jul 26, 2011.

  1. #1
    Hi,
    I came across an article which said that one should compress one's files when fetched from server because that really speeds up the site loading time.

    Currently, in my Global.asax file , I am using the following code :

     void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
    
            HttpApplication app = sender as HttpApplication;
            string acceptEncoding = app.Request.Headers["Accept-Encoding"];
            Stream prevUncompressedStream = app.Response.Filter;
    
            if (!(app.Context.CurrentHandler is Page ||
                app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
                app.Request["HTTP_X_MICROSOFTAJAX"] != null)
                return;
    
            if (acceptEncoding == null || acceptEncoding.Length == 0)
                return;
    
            acceptEncoding = acceptEncoding.ToLower();
    
            if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
            {
                // defalte
                app.Response.Filter = new DeflateStream(prevUncompressedStream,
                    CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "deflate");
            }
            else if (acceptEncoding.Contains("gzip"))
            {
                // gzip
                app.Response.Filter = new GZipStream(prevUncompressedStream,
                    CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "gzip");
            }
    
    
        } 
    Code (markup):
    The following code compresses the html and aspx files but doesnt compress with JS and CSS..
    So kindly you could provide me with some snippet or point me in the correct direstion.

    Thanks
     
    akshaykalia, Jul 26, 2011 IP
  2. geekstrack

    geekstrack Well-Known Member

    Messages:
    72
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    121
    #2
    add this code to your web.config
    <system.webServer>
    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
    <add mimeType="text/*" enabled="true"/>
    <add mimeType="message/*" enabled="true"/>
    <add mimeType="application/javascript" enabled="true"/>
    <add mimeType="*/*" enabled="false"/>
    dynamicTypes>
    <staticTypes>
    <add mimeType="text/*" enabled="true"/>
    <add mimeType="message/*" enabled="true"/>
    <add mimeType="application/javascript" enabled="true"/>
    <add mimeType="*/*" enabled="false"/>
    staticTypes>
    httpCompression>
    <urlCompression doStaticCompression="true" doDynamicCompression="true"/>


    system.webServer>
     
    geekstrack, Feb 23, 2012 IP