通过GZIP或DEFLATE方式对所有页面进行压缩,会大大缩小页面传输的容量。

可以使用Fiddler2来观察使用压缩后页面大小的变化。

在项目中添加Global.asax,然添加如下代码:

 1         protected void Application_BeginRequest(object sender, EventArgs e)
 2         {
 3             HttpApplication app = (HttpApplication)sender;
 4             string acceptEncoding = app.Request.Headers["Accept-Encoding"];
 5             Stream prevUncompressedStream = app.Response.Filter;
 6             if (acceptEncoding == null || acceptEncoding.Length == 0return;
 7             acceptEncoding = acceptEncoding.ToLower();
 8             if (acceptEncoding.Contains("gzip"))
 9             {
10                 // gzip
11                 app.Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
12                 app.Response.AppendHeader("Content-Encoding""gzip");
13             }
14             else if (acceptEncoding.Contains("deflate"))
15             {
16                 // defalte
17                 app.Response.Filter = new DeflateStream(prevUncompressedStream, CompressionMode.Compress);
18                 app.Response.AppendHeader("Content-Encoding""deflate");
19             }
20         }

 

 

修正:

这种方法是我无意中在网上找到的,我在实际的项目中并没有使用,压缩的效果是有的,但是对服务器端的资源占用情况我没有测试过,所以不是太清楚这个和IIS中设置压缩的方式那个好。暂时只是做一个代码备份,以后用空在研究。

另外,这个方法还是有缺点的,我在试验中发现使用后会导致.net自带的TreeView的小图标失效。原因是TreeView在使用默认的小图标时,图片文件是通过WebResource.axd获取的,而压缩后就无法获取到图片了,所以在代码开始时对请求的文件进行过滤,对WebResource.axd不进行压缩。

 

posted on 2008-11-14 14:42  *小小黄*  阅读(488)  评论(2编辑  收藏  举报