稍微研究了一下頁面壓縮...
壓縮後的頁面空間變小,可以稍微的降低網頁的流量,提昇傳輸的速度...
廢話不多說 來看程式囉
- usingSystem;
- usingSystem.IO;
- usingSystem.IO.Compression;
- usingSystem.Web;
- namespaceLibrary.framework
- {
- ///<!--HTTP壓縮輸出-->
- ///<summary>
- ///HTTP壓縮輸出-designByPhoenix2008-
- ///</summary>
- ///Update:2008.09.08
- ///Developer:Phoenix
- ///Version:1.0.0918
- publicclassHttpCompression:IHttpModule
- {
- #regionIHttpModule成員
- voidIHttpModule.Dispose()
- {
- //Dispose
- }
- voidIHttpModule.Init(HttpApplicationcontext)
- {
- //加入壓縮事件
- context.BeginRequest+=newEventHandler(context_BeginRequest);
- }
- #endregion
- voidcontext_BeginRequest(objectsender,EventArgse)
- {
- //提取Application
- HttpApplicationapp=(HttpApplication)sender;
- //判斷是否為*.axd(此檔不可壓縮)
- if(app.Request.Path.Contains("axd"))
- return;
- //提取支援的壓縮格式
- stringencodiongs=app.Request.Headers.Get("Accept-Encoding");
- //判斷是否支援壓縮
- if(string.IsNullOrEmpty(encodiongs))
- {
- app.Context.Items["Compression"]="Compressiondisabled";
- return;
- }
- //提取輸出資料流
- StreamFilter=app.Response.Filter;
- //將壓縮格式轉小寫
- encodiongs=encodiongs.ToLower();
- //判斷是否支援Gzip
- if(encodiongs.Contains("gzip"))
- {
- //將壓縮過的資料流取代原本的資料流
- app.Response.Filter=newGZipStream(Filter,CompressionMode.Compress);
- //將壓縮格式加入至標頭
- app.Response.AppendHeader("Content-Encoding","gzip");
- //將壓縮格式寫入事件
- app.Context.Trace.Warn("Gzipenabled");
- app.Context.Items["Compression"]="Gzipenabled";
- }
- else
- {
- //將壓縮過的資料流取代原本的資料流
- app.Response.Filter=newDeflateStream(Filter,CompressionMode.Compress);
- //將壓縮格式加入至標頭
- app.Response.AppendHeader("Content-Encoding","deflate");
- //將壓縮格式寫入事件
- app.Context.Trace.Warn("Deflateenabled");
- app.Context.Items["Compression"]="Deflateenabled";
- }
- }
- }
- }
基本上 ... ScriptResource.axd 這個檔案是不可以壓縮的(不然後果嚴重) 瀏覽器不會自己解壓縮
所以我把這個檔案排除
再來最重要的 是在Web.config 內將其加入至httpModules標籤內
<add name="HttpCompression" type="Library.framework.HttpCompression"/>
再來一個 可以在頁面底部標示啟動哪種壓縮模式(請自行加入文件底部)
<%=Context.Items["Compression"].ToString() %>
以上