15 May 2008 - 2:23 PM / by Dominic Pettifer. 12 Comments for GZip compress your website's HTML/CSS/Script in code.
Cool C# Snippets - Dynamically GZIP compress the HTML response of your website in code, without having to configure IIS directly. Make massive savings on your websites bandwidth.
I recently found a way to GZIP compress the HTML, CSS and Javascript output from an ASP.NET website, dynamically in code. GZIP compression can drastically reduce the file sizes for any text based file served to the client. This includes the raw HTML, CSS, Javascript files, even plain XML or CSV, but it can't compress images, media and binary files. Normally, you'd set this on the server, but what if you dont have access to the server.
First create a Global.asax file in your web root and put the following line in it, deleting everything thats there currently...
<%@ Application Language="C#" Inherits="Global" %>
Then create a Global.cs file in your APP_CODE folder and put the following code in...
using System;
using System.IO.Compression;
public class Global : System.Web.HttpApplication
{
public Global()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.PostReleaseRequestState +=
new EventHandler(Global_PostReleaseRequestState);
}
private void Global_PostReleaseRequestState(
object sender, EventArgs e)
{
string contentType = Response.ContentType;
if (contentType == "text/html" ||
contentType == "text/css")
{
Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
string acceptEncoding =
Request.Headers["Accept-Encoding"];
if(acceptEncoding != null)
{
if (acceptEncoding.Contains("gzip"))
{
Response.Filter = new GZipStream(
Response.Filter, CompressionMode.Compress);
Response.AppendHeader(
"Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
Response.Filter = new DeflateStream(
Response.Filter, CompressionMode.Compress);
Response.AppendHeader(
"Content-Encoding", "deflate");
}
}
}
}
}The browser will tell the server whether it supports GZIP or DEFLATE compression (via the Accept-Encoding header). If its an older browser that doesn't support compression, it will just be sent as uncompressed HTML and your site will still work.
The magic happens with the following lines...
Response.Filter = new GZipStream(
Response.Filter, CompressionMode.Compress);
Response.AppendHeader("Content-Encoding", "gzip");Response.Filter (also available from your ASPX pages) exposes a Stream which you override with a GZipStream object, this will cause the raw text response to get compressed, while telling the browser this the response is compressed with the second line Response.AppendHeader.
The reason we put this in the Global_PostReleaseRequestState event is because it allows us to target all files, not just ASPX pages.
Pay attention to the line if (contentType == "text/html" || contentType == "text/css"), I had an issue where I was using the ASP.NET AJAX extensions Control Toolkit which was supplying it's own external javascript files that were already GZIP compressed, and since it was trying to compress an already compressed file, it was screwing it up causing issues and throwing script errors on the client, because the browser couldn't read the script files. So be aware of this, if you have complete control over your external JavaScript files then could probably add the code...
|| contentType == "application/x-javascript" || contentType == "text/javascript"
...to that IF statement.
FYI, I tried adding this code to an application I was working on at Conscia. The client wouldn't let us turn GZIP compression on their own servers, and we didn't have any access to them. Page sizes were around 150-200KB but after adding this code they now sit at around 20-30KB, a massive improvement which would benefit the particular slow network this application was being made to run on.
Page loads times were quicker and the application seemed noticably more responsive. So your benefits are lowered costs and an improved user experience.
It working good in MVC website. Thanks.
Posted on 9 March 2011 - 3:19 AM / by Khuong Vo
I want to apply this compression only for few .aspx pages in my application?
How can I do this.
Please help me in this.
Thanks in advance.
Sangeetha
Posted on 17 May 2010 - 7:12 AM / by Sangeetha
Try the two magic lines in Page_PreRender event.It Works!
protected void Page_PreRender(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
}
Posted on 18 December 2011 - 1:55 AM / by Vinay
An SEO Company USA hires the best employees for their organization, who have the ability to face the new challenges and accomplish the need of clients. Indian SEO companies offer high quality services at affordable rates as they find qualified resources easily. If you are seeking out instant result, hire a best SEO company London, who is fully experienced and has a good rapport in the online market. As soon as you hire an Indian company, it starts showing you result (WEB Development India).
Posted on 3 January 2012 - 12:54 PM / by WEB Development India
hi..
When i add this it shows the blue color underline on this line
this.PostReleaseRequestState
and also the underline shows for all Response.
Posted on 6 April 2010 - 1:02 PM / by venkat
The Script and Css compress doesnt work in IIS but if run my website using visual studio 2005 it works.
does i have to change something in IIS ?
Posted on 29 January 2010 - 5:08 PM / by jmpena
To compress the css and javascript use following
this.PreRequestHandlerExecute += new EventHandler(Global_PostReleaseRequestState);
Posted on 1 January 2010 - 8:13 AM / by Amit
I don't know why but I got it to work on the localhost but not my server. Very strange.
Posted on 25 September 2009 - 11:31 AM / by Jesse
Just an idea, but wouldnt it be better to implement this into a IHttpHandler?
You would still get the per-request-processing but it will allow you greater control over files/folders?
Stueh.
Posted on 19 July 2009 - 11:30 PM / by Stu
Hi Dominic,
I have just gone through the article its working fine at my end for HTML.
Could you please suggest me how to cache the gzipped version of HTML so that the content is not zippped for each request ?
Your reply would be helpfull for me.
Thanks in Advance,
Karthik.
Posted on 8 June 2009 - 6:37 AM / by Karthik Reddy Chintaparthi
Hello,
I have my application on .net 2.0 i also not able to compress the css and javascript files.
Posted on 27 May 2009 - 9:54 AM / by Dharmender
Do we need to make changes in Metabase.xml file for this to work?
Posted on 27 October 2009 - 6:17 AM / by Anonymous
Thanks for the code! I've had a go at implementing it but it only seems to GZip the .aspx pages and even with the extra line in the IF statement it ignores CSS or Javascript files.
Only thing I can think of is that I'm running .NET 3.5 and it was made for 2.0?
Many thanks,
Ian.
Posted on 7 April 2009 - 3:29 PM / by Ian Black
Do we need to make changes in the Metabase.xml file for the above code to work? Please reply. Or Should we Change anything else?
Posted on 27 October 2009 - 6:22 AM / by Anonymous
Every one knows that humen's life seems to be expensive, nevertheless some people need money for different issues and not every man gets big sums cash. Thence to receive some <a href="http://bestfinance-blog.com/topics/credit-loans">credit loans</a> or student loan should be a correct solution.
Posted on 11 May 2011 - 8:42 AM / by GriffinDebbie
Don't you realize what real freedom looks like? At time you don't write your wars essay paper, but writing service provides you with homework help, you would see the autonomy.
Posted on 16 May 2011 - 6:36 PM / by miscellaneous essays paper
Some students look for the thesis research just about this post. If they get know about your smashing research, they will credibly order the dissertation writing.
Posted on 16 May 2011 - 11:32 PM / by dissertation writing service
Some days ago I downloaded the cool ringtones with the help of the free ringtones for your phone site and was definitely happy.
Posted on 18 May 2011 - 3:56 AM / by tones for free
Newest styles of <a href="http://www.christianlouboutinreplicacl.com/"><strong>christian louboutin high heels</strong></a> in hot sale now, <a href="http://www.christianlouboutinreplicacl.com/"><strong>Christian Louboutin Knockoffs</strong></a> shoes sale now, buy <a href="http://www.christianlouboutinreplicacl.com/"><strong>christian louboutin replica</strong></a> in our online uk store .your shoes sales prices will save.
Posted on 22 September 2011 - 2:34 AM / by christian louboutin replica
If you don't cruise after what you need, you'll never have it. If you don't request, the response is continually no. If you don't get used to dissertation writing service , you're continually in the consistent place.
Posted on 29 September 2011 - 10:39 PM / by dissertation writing
That is simple to buy custom essay papers and lots of people do not get know that such good enough stuff close to this topiccould subsist and just because of it they buy research papers.
Posted on 1 October 2011 - 6:20 AM / by buy research paper
Do not know a proper way to begin your dissertations completing? You not have to worry, because a professional buy dissertation service would assist with essay thesis of any branch of science.
Posted on 1 October 2011 - 9:23 PM / by custom thesis
I generally do my business fast and I require seo submission issues provided by site submission services. But, I doubt what company to select! If you know various good services, will you tell me?
Posted on 3 October 2011 - 1:11 PM / by submission services
Very sensational theme. With content being so decisive online, this is a tough outline for achieve new on that people will use for thesis writing service.
Posted on 3 October 2011 - 6:06 PM / by thesis writing
<a href="http://www.louisvuihhttonoutletbbh.com">louis vuitton</a>
[url=http://www.louisvuissttonoutletbbh.com]louis vuitton[/url]
Posted on 1 December 2011 - 11:50 AM / by coach
The dissertation topic should be properly written by experienced thesis writing service, if some people are willing to present writing skillfulness. Hence, that’s apparently that you really know the correct way to finish a perfect thought related to this good post. Thank you for sharing it.
Posted on 5 October 2011 - 10:56 AM / by thesis
Have you ever heard about academic writing jobs service? I just want to say that your thoughts just about this good post is smashing! Thank you a lot for creating this!
Posted on 4 December 2011 - 3:11 PM / by Freelance writing work
These dominoes are getting bigger and bigger every year. (from the blog And So It Begins )
And YouTube still auto-fucking-plays videos!! This is TWO-THOUSAND-AND-FUCKING-TWELVE FFS!!!
about 20 hours ago from webOn a side-note, YouTube's commenting system is god-awful atrocious dreadful horrible horrible horrible!! Constant meaningless error messages
about 20 hours ago from webJavaScript is slow mmmkay http://t.co/NbB4eQjw - Actually, no, it's not http://t.co/kpGEIoPO #nodejs
about 20 hours ago from webTFS: It's super expensive, so it must be brilliant, right? Like Sharepoint #tekpubtfstitlesuggestion
5:22 PM February 3rd from web