Friday, January 23, 2009

Quick Tip: C# GZip content

A quick post with a simple trick that let us reduce instantly every Ajax interaction over our C#.NET application:

[-] public void GZResponse() {
if(-1 < Convert.ToString(Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip")){
Response.AddHeader("Content-Encoding", "gzip");
Response.Filter = new System.IO.Compression.GZipStream(
Response.Filter,
System.IO.Compression.CompressionMode.Compress
);
}
}

The good part is that precedent code, whenever we were using Response.Write, became automatically compatible. Above code could be used to serve JavaScript or css files too:


[+] public void GZResponse(){}

[-] protected void Page_Load(object sender, EventArgs e)
{
GZResponse();
Response.AddHeader("Content-Type", "text/javascript");
Response.WriteFile("jquery.min.js");
}


That's it :-)

P.S. for file serving I suggest a cache system for pre gzipped files

No comments:

Post a Comment