當我們壓縮我的Response後再傳到Client端時,可以明顯節省寬頻. 提升Site的效能. 現在的瀏覽器大部分都支援Gzip,Deflate壓縮. 同時我們還可以刪除一些空白
段,空行,註釋等以使得HTML文件的尺寸變得更小. 讓我們先來實現壓縮與刪除空白類, 繼承自Stream類:
1: /// <summary>
2: /// CompressWhitespaceFilter
3: /// </summary>
4: public class CompressWhitespaceFilter : Stream
5: {
6: private GZipStream _contentGZipStream;
7: private DeflateStream _content_DeflateStream;
8: private Stream _contentStream;
9: private CompressOptions _compressOptions;
10:
11:
12: /// <summary>
13: /// Initializes a new instance of the <see cref="CompressWhitespaceFilter"/> class.
14: /// </summary>
15: /// <param name="contentStream">The content stream.</param>
16: /// <param name="compressOptions">The compress options.</param>
17: public CompressWhitespaceFilter(Stream contentStream, CompressOptions compressOptions)
18: {
19: if (compressOptions == CompressOptions.GZip)
20: {
21: this._contentGZipStream = new GZipStream(contentStream, CompressionMode.Compress);
22: this._contentStream = this._contentGZipStream;
23: }
24: else if (compressOptions == CompressOptions.Deflate)
25: {
26: this._content_DeflateStream = new DeflateStream(contentStream,CompressionMode.Compress);
27: this._contentStream = this._content_DeflateStream;
28: }
29: else
30: {
31: this._contentStream = contentStream;
32: }
33: this._compressOptions = compressOptions;
34: }
35:
36: public override bool CanRead
37: {
38: get { return this._contentStream.CanRead; }
39: }
40:
41: public override bool CanSeek
42: {
43: get { return this._contentStream.CanSeek; }
44: }
45:
46: public override bool CanWrite
47: {
48: get { return this._contentStream.CanWrite; }
49: }
50:
51: public override void Flush()
52: {
53: this._contentStream.Flush();
54: }
55:
56: public override long Length
57: {
58: get { return this._contentStream.Length; }
59: }
60:
61: public override long Position
62: {
63: get
64: {
65: return this._contentStream.Position;
66: }
67: set
68: {
69: this._contentStream.Position = value;
70: }
71: }
72:
73: public override int Read(byte[] buffer, int offset, int count)
74: {
75: return this._contentStream.Read(buffer, offset, count);
76: }
77:
78: public override long Seek(long offset, SeekOrigin origin)
79: {
80: return this._contentStream.Seek(offset, origin);
81: }
82:
83: public override void SetLength(long value)
84: {
85: this._contentStream.SetLength(value);
86: }
87:
88: public override void Write(byte[] buffer, int offset, int count)
89: {
90: byte[] data = new byte[count + 1];
91: Buffer.BlockCopy(buffer, offset, data, 0, count);
92:
93: string strtext = System.Text.Encoding.UTF8.GetString(buffer);
94: strtext = Regex.Replace(strtext, "^\\s*", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
95: strtext = Regex.Replace(strtext, "\\r\\n", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
96: strtext = Regex.Replace(strtext, "<!--*.*?-->", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
97:
98: byte[] outdata = System.Text.Encoding.UTF8.GetBytes(strtext);
99: this._contentStream.Write(outdata, 0, outdata.GetLength(0));
100: }
101: }
102:
103: /// <summary>
104: /// CompressOptions
105: /// </summary>
106: /// <seealso cref="http://en.wikipedia.org/wiki/Zcat#gunzip_and_zcat"/>
107: /// <seealso cref="http://en.wikipedia.org/wiki/DEFLATE"/>
108: public enum CompressOptions
109: {
110: GZip,
111: Deflate,
112: None
113: }
上面的程式碼使用正規表示式替換字串,你可以修改那些正規表示式來滿足你的需求. 我們同時使用了GZipStream與DeflateStream實現了壓縮. 好的,接下來與
HttpModule結合:
1: /// <summary>
2: /// CompressWhitespaceModule
3: /// </summary>
4: public class CompressWhitespaceModule : IHttpModule
5: {
6: #region IHttpModule Members
7:
8: /// <summary>
9: /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
10: /// </summary>
11: public void Dispose()
12: {
13: // Nothing to dispose;
14: }
15:
16: /// <summary>
17: /// Initializes a module and prepares it to handle requests.
18: /// </summary>
19: /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
20: public void Init(HttpApplication context)
21: {
22: context.BeginRequest += new EventHandler(context_BeginRequest);
23: }
24:
25: /// <summary>
26: /// Handles the BeginRequest event of the context control.
27: /// </summary>
28: /// <param name="sender">The source of the event.</param>
29: /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
30: void context_BeginRequest(object sender, EventArgs e)
31: {
32: HttpApplication app = sender as HttpApplication;
33: if (app.Request.RawUrl.Contains(".aspx"))
34: {
35: HttpContext context = app.Context;
36: HttpRequest request = context.Request;
37: string acceptEncoding = request.Headers["Accept-Encoding"];
38: HttpResponse response = context.Response;
39: if (!string.IsNullOrEmpty(acceptEncoding))
40: {
41: acceptEncoding = acceptEncoding.ToUpperInvariant();
42: if (acceptEncoding.Contains("GZIP"))
43: {
44: response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.GZip);
45: response.AppendHeader("Content-encoding", "gzip");
46: }
47: else if (acceptEncoding.Contains("DEFLATE"))
48: {
49: response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.Deflate);
50: response.AppendHeader("Content-encoding", "deflate");
51: }
52: }
53: response.Cache.VaryByHeaders["Accept-Encoding"] = true;
54: }
55: }
56:
57: #endregion
58: }
HttpApplication.BeginRequest 事件是 在 ASP.NET 響應請求時作為 HTTP 執行管線鏈中的第一個事件發生。
在WEB.CONFIG中你還需要配置:
1: <httpModules>
2: <add name="CompressWhitespaceModule" type="MyWeb.CompressWhitespaceModule" />
3: </httpModules>
我們來看一下效果,下面沒有使用時, 4.8KB
接著看,處理過後的效果,Cotent-Encoding: gzip, filezie: 1.6KB
很簡單,你可以按需求來增加更多的功能. 希望對您開發有幫助.