实现页面的GZip或Deflate压缩。
.NET Framework里
System.IO.Compression下有两个可用于页面压缩的类,GZipStream和 DeflateStream.
---
在页面被传输之前,需要获取发出请求的客户端所采用的解码形式。
可以通过Request.Headers["Accept-Encoding"]来获取。
---
在页面被压缩之前,需要获取页面实体主体,可通过
Response.Filter来获取(Stream类型)
------
示例代码:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10using System.IO;
11using System.IO.Compression;
12
13/// <summary>
14/// GzipDeflate 的摘要说明
15/// </summary>
16public class GzipDeflate:IHttpModule
17{
18 public GzipDeflate()
19 {
20 //
21 // TODO: 在此处添加构造函数逻辑
22 //
23 }
24 public void Init(HttpApplication app)
25 {
26 app.BeginRequest += new EventHandler(app_BeginRequest);
27 }
28
29 void app_BeginRequest(object sender, EventArgs e)
30 {
31 //HTTP头域可分为四类:通用头、请求头、响应头、实体头。
32 HttpApplication app=(HttpApplication)sender;
33 string acceptEncoding = app.Request.Headers["Accept-Encoding"]; //客户端支持的解码方式。属于请求头。
34 Stream requestStream = app.Response.Filter;
35 acceptEncoding = acceptEncoding.ToLower();
36 if(acceptEncoding.Contains("gzip"))
37 {
38 app.Response.Filter = new GZipStream(requestStream, CompressionMode.Compress);
39 app.Response.AppendHeader("Content-Encoding", "gzip");
40 }
41 else if(acceptEncoding.Contains("deflate"))
42 {
43 app.Response.Filter = new DeflateStream(requestStream, CompressionMode.Compress);
44 app.Response.AppendHeader("Content-Encoding", "deflate"); //属于实体头。
45 }
46 }
47 public void Dispose()
48 {
49
50 }
51}
52
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10using System.IO;
11using System.IO.Compression;
12
13/// <summary>
14/// GzipDeflate 的摘要说明
15/// </summary>
16public class GzipDeflate:IHttpModule
17{
18 public GzipDeflate()
19 {
20 //
21 // TODO: 在此处添加构造函数逻辑
22 //
23 }
24 public void Init(HttpApplication app)
25 {
26 app.BeginRequest += new EventHandler(app_BeginRequest);
27 }
28
29 void app_BeginRequest(object sender, EventArgs e)
30 {
31 //HTTP头域可分为四类:通用头、请求头、响应头、实体头。
32 HttpApplication app=(HttpApplication)sender;
33 string acceptEncoding = app.Request.Headers["Accept-Encoding"]; //客户端支持的解码方式。属于请求头。
34 Stream requestStream = app.Response.Filter;
35 acceptEncoding = acceptEncoding.ToLower();
36 if(acceptEncoding.Contains("gzip"))
37 {
38 app.Response.Filter = new GZipStream(requestStream, CompressionMode.Compress);
39 app.Response.AppendHeader("Content-Encoding", "gzip");
40 }
41 else if(acceptEncoding.Contains("deflate"))
42 {
43 app.Response.Filter = new DeflateStream(requestStream, CompressionMode.Compress);
44 app.Response.AppendHeader("Content-Encoding", "deflate"); //属于实体头。
45 }
46 }
47 public void Dispose()
48 {
49
50 }
51}
52
<h3>
心静似高山流水不动,心清若巫峰雾气不沾。
</h3>
心静似高山流水不动,心清若巫峰雾气不沾。
</h3>