文章转自:爱符号 http://www.afuhao.com/article_articleId-132.shtml
你的网站如果是asp.net开发的,有没有考虑压缩输出内容?
有的人知道IIS是支持压缩输出的,但是有的时候后台有的页面是动态输出的,如果开启了动态压缩,就会导致要动态输出完成后,才会看到页面结果。
所以这个时候就会有一个纠结的问题,如果开启了动态压缩,那么动态输出的页面就会很慢。
但是不开启压缩,又会浪费很多传输资源。
那么当你发现别的都帮不了你的时候,自己才是最靠得住的!
声明一下:这个模块的源代码我直接找的,然后优化一些地方,如果你曾经看到过,也不用奇怪。可能你会问怎么不自己写,其实这种只要没毛病又效率高的现成代码何必自己写呢。
CompressionModule.cs
- namespace Symbol.Web {
- using System;
- using System.IO.Compression;
- using System.Web;
- public class CompressionModule : IHttpModule {
- void IHttpModule.Dispose() { }
- void IHttpModule.Init(HttpApplication context) {
- context.PreRequestHandlerExecute += new EventHandler(context_PostReleaseRequestState);
- }
- void context_PostReleaseRequestState(object sender, EventArgs e) {
- HttpApplication app = (HttpApplication)sender;
- //这里做一个过滤,后台不需要压缩,具体可以自己写一些判断,
- //我这里只是当访问路径有 /area开头时不允许压缩,因为后台有时候是动态输出,用了压缩就没有意义了
- if (app.Request.Path.StartsWith("/area/", StringComparison.OrdinalIgnoreCase))
- return;
- //当前为aspx页面,并且不是WEBFORM回调时,就开启压缩
- if (app.Context.CurrentHandler is System.Web.UI.Page && app.Request["HTTP_X_MICROSOFTAJAX"] == null) {
- if (IsEncodingAccepted(GZIP)) {//优先使用GZIP压缩
- app.Response.Filter = new GZipStream(app.Response.Filter, CompressionMode.Compress);
- SetEncoding(GZIP);
- } else if (IsEncodingAccepted(DEFLATE)) {//Deflate也可以
- app.Response.Filter = new DeflateStream(app.Response.Filter, CompressionMode.Compress);
- SetEncoding(DEFLATE);
- }
- }
- }
- private static readonly string GZIP = "gzip";
- private static readonly string DEFLATE = "deflate";
- //判断客户端是否支持指定的压缩
- private static bool IsEncodingAccepted(string encoding) {
- HttpContext context = HttpContext.Current;
- return context.Request.Headers["Accept-Encoding"] != null && context.Request.Headers["Accept-encoding"].Contains(encoding);
- }
- //开启了压缩后,需要设置一下返回的编码类型,方便客户端解压缩
- private static void SetEncoding(string encoding) {
- HttpContext.Current.Response.AppendHeader("Content-Encoding", encoding);
- }
- }
- }
web.config配置
- <!--这是放在<system.web>节点的,iis5,iis6读取这里的-->
- <httpModules>
- <add name="CompressionModule" type="Symbol.Web.CompressionModule, www.afuhao.com"/><!--www.afuhao.com是你的程序集名称-->
- </httpModules>
- <!--这是放到<system.webServer>节点的,iis7读取这里的-->
- <modules runAllManagedModulesForAllRequests="true">
- <add name="CompressionModule" type="Symbol.Web.CompressionModule, www.afuhao.com"/><!--www.afuhao.com是你的程序集名称-->
- </modules>
网页GZIP压缩检测 http://tool.chinaz.com/Gzips/
下面是效果图: