enable gzip compression asp.net

Web .Config

<system.webServer>
<httpCompression>
<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>

 

 

 

Global ASAX

private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
string contentType = Response.ContentType; // Get the content type.

// Compress only html and stylesheet documents.
if (contentType == “text/html” || contentType == “text/css”)
{
// Get the Accept-Encoding header value to know whether zipping is supported by the browser or not.
string acceptEncoding = Request.Headers[“Accept-Encoding”];

if (!string.IsNullOrEmpty(acceptEncoding))
{
// If gzip is supported then gzip it else if deflate compression is supported then compress in that technique.
if (acceptEncoding.Contains(“gzip”))
{
// Compress and set Content-Encoding header for the browser to indicate that the document is zipped.
Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress);
Response.AppendHeader(“Content-Encoding”, “gzip”);
}
else if (acceptEncoding.Contains(“deflate”))
{
// Compress and set Content-Encoding header for the browser to indicate that the document is zipped.
Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter, System.IO.Compression.CompressionMode.Compress);
Response.AppendHeader(“Content-Encoding”, “deflate”);
}
}
}
}

 

Advertisements