<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dotnet thoughts &#187; HTTP Compression</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/http-compression/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>a dotnet developer&#039;s technical blog</description>
	<lastBuildDate>Wed, 08 Feb 2012 03:18:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Http Compression in ASP.Net</title>
		<link>http://www.dotnetthoughts.net/2010/01/05/http-compression-in-asp-net/</link>
		<comments>http://www.dotnetthoughts.net/2010/01/05/http-compression-in-asp-net/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 12:40:18 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[HTTP Compression]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=687</guid>
		<description><![CDATA[Yesterday I got a chance to attend web performance optimization team meeting, and they suggested, HTTP Compression will help to reduce the Bandwidth and thus improves the performance. Later I come to know some of other teams in my organization &#8230; <a href="http://www.dotnetthoughts.net/2010/01/05/http-compression-in-asp-net/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Yesterday I got a chance to attend web performance optimization team meeting, and they suggested, HTTP Compression will help to reduce the Bandwidth and thus improves the performance. Later I come to know some of other teams in my organization are using these techniques in their web applications. I found few implementations, and the code is written in Global.asax. But the problem with this approach is the code is not reusable. I thought of implementing it an Http Module for compressing the HTTP response. For more information about HttpModules, check <a href="http://support.microsoft.com/kb/307996" target="_blank">MSDN</a>.</p>
<p>Here is the code of Compression Module.</p>
<pre class="brush: csharp; title: ; notranslate">
public class CompressionModule : IHttpModule
{
    private HttpApplication httpApplication;
    private string acceptEncoding;
    private const string DEFLATE = &quot;deflate&quot;;
    private const string GZIP = &quot;gzip&quot;;
    private const string AJAX = &quot;HTTP_X_MICROSOFTAJAX&quot;;
    private const string WEBSERVICE = &quot;SyncSessionlessHandler&quot;;

    /// &lt;summary&gt;
    /// Disposes of the resources (other than memory) used by the module that implements &lt;see cref=&quot;T:System.Web.IHttpModule&quot;/&gt;.
    /// &lt;/summary&gt;
    public void Dispose()
    {
        //Do nothing
    }

    /// &lt;summary&gt;
    /// Initializes a module and prepares it to handle requests.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;context&quot;&gt;An &lt;see cref=&quot;T:System.Web.HttpApplication&quot;/&gt; that provides access to the methods, properties, and events common to all application objects within an ASP.NET application&lt;/param&gt;
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        this.httpApplication = context;
    }

    /// &lt;summary&gt;
    /// Handles the BeginRequest event of the context control.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;sender&quot;&gt;The source of the event.&lt;/param&gt;
    /// &lt;param name=&quot;e&quot;&gt;The &lt;see cref=&quot;System.EventArgs&quot;/&gt; instance containing the event data.&lt;/param&gt;
    private void context_BeginRequest(object sender, EventArgs e)
    {
        if (IsEncodingSupported)
        {
            //Converting the Accept encoding to lower, it can be gZip, GZip, Gzip
            this.acceptEncoding = acceptEncoding.ToLower();
            Stream prevUncompressedStream = this.httpApplication.Response.Filter;

            //First checks whether deflate compression is supported or not.
            //Because Deflate offers better compression compared to GZip

            if (acceptEncoding.Contains(DEFLATE) || acceptEncoding == &quot;*&quot;)
            {
                // defalte
                this.httpApplication.Response.Filter = new DeflateStream(prevUncompressedStream,
                    CompressionMode.Compress);
                this.httpApplication.Response.AppendHeader(&quot;Content-Encoding&quot;, DEFLATE);
            }
            else if (acceptEncoding.Contains(GZIP))
            {
                // gzip
                this.httpApplication.Response.Filter = new GZipStream(prevUncompressedStream,
                    CompressionMode.Compress);
                this.httpApplication.Response.AppendHeader(&quot;Content-Encoding&quot;, GZIP);
            }
        }
    }

    /// &lt;summary&gt;
    /// Gets a value indicating whether this instance is encoding supported.
    /// &lt;/summary&gt;
    /// &lt;value&gt;
    /// 	&lt;c&gt;true&lt;/c&gt; if this instance is encoding supported; otherwise, &lt;c&gt;false&lt;/c&gt;.
    /// &lt;/value&gt;
    private bool IsEncodingSupported
    {
        get
        {
            //Check wheather the Request is for Page or Web Service.
            //Also check wheather it an AJAX Request.
            this.acceptEncoding = this.httpApplication.Request.Headers[&quot;Accept-Encoding&quot;];

            if (!this.httpApplication.Request.RawUrl.Contains(&quot;.aspx&quot;) ||
                this.httpApplication.Request[AJAX] != null)
            {
                return (false);
            }
            //Check whether browser supports compression.
            if (acceptEncoding == null || acceptEncoding.Length == 0)
            {
                return (false);
            }
            return true;
        }
    }
}
</pre>
<p>As the code is in App_Code folder, you need to register the http module in the Web.Config file. </p>
<pre class="brush: xml; title: ; notranslate">
&lt;httpModules&gt;
      &lt;add name=&quot;CompressionModule&quot; type=&quot;CompressionModule, App_Code&quot;/&gt;
&lt;/httpModules&gt;
</pre>
<p>If you are using IIS 7 the settings will be different like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;system.webServer&gt;
&lt;modules&gt;
      &lt;add name=&quot;CompressionModule&quot; type=&quot;CompressionModule, App_Code&quot;/&gt;
&lt;/modules&gt;
&lt;/system.webServer&gt;
</pre>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2008/05/08/using-iocompression-namespace/" title="Permanent link to Using IO.Compression namespace">Using IO.Compression namespace</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/07/28/filenot-found-exception-application_error-event-in-global-asax/" title="Permanent link to FileNot Found exception &#8211; Application_Error event in Global.asax">FileNot Found exception &#8211; Application_Error event in Global.asax</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/04/19/convert-string-to-enum/" title="Permanent link to Convert string to enum">Convert string to enum</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/11/03/simple-url-rewriting-in-asp-net-with-csharp/" title="Permanent link to Simple URL Rewriting in ASP.Net with C#">Simple URL Rewriting in ASP.Net with C#</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/07/15/dropdownlist-findbytext-problem/" title="Permanent link to Dropdownlist FindByText Problem">Dropdownlist FindByText Problem</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/01/05/http-compression-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

