.NET Framework里
System.IO.Compression下有两个可用于页面压缩的类,GZipStream和 DeflateStream.
---
在页面被传输之前,需要获取发出请求的客户端所采用的解码形式。
可以通过Request.Headers["Accept-Encoding"]来获取。
---
在页面被压缩之前,需要获取页面实体主体,可通过
Response.Filter来获取(Stream类型)
------
示例代码:
1
using System;
2
using System.Data;
3
using System.Configuration;
4
using System.Web;
5
using System.Web.Security;
6
using System.Web.UI;
7
using System.Web.UI.WebControls;
8
using System.Web.UI.WebControls.WebParts;
9
using System.Web.UI.HtmlControls;
10
using System.IO;
11
using System.IO.Compression;
12
13
/// <summary>
14
/// GzipDeflate 的摘要说明
15
/// </summary>
16
public 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52
