August 29, 2012

ASP.Net - Enable GZip Compression

Enable GZip Compression By using Web.Config File

Past the below code inside the Configuration tag

<!-- Enabling Compression Starts Here -->
 
<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>
 
<!-- Compression Ends Here -->


Enable GZip Compression By using Global.asax

Past the below code inside the Global.asax File

private const string GZIP = "gzip";
private const string DEFLATE = "deflate";
 
void Application_ReleaseRequestState(object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;
    if (app.Context.CurrentHandler is Page && app.Request["HTTP_X_MICROSOFTAJAX"] == null)
    {
        if (IsEncodingAccepted(DEFLATE))
        {
            app.Response.Filter = new System.IO.Compression.DeflateStream(app.Response.Filter, System.IO.Compression.CompressionMode.Compress);
            SetEncoding(DEFLATE);
        }
        else if (IsEncodingAccepted(GZIP))
        {
            app.Response.Filter = new System.IO.Compression.GZipStream(app.Response.Filter, System.IO.Compression.CompressionMode.Compress);
            SetEncoding(GZIP);
        }
    }
}
 
private static void SetEncoding(string encoding)
{
    HttpContext.Current.Response.AppendHeader("Content-encoding", encoding);
}

No comments:

Post a Comment