產生靜態頁,為什麼不產生壓縮靜態頁?

來源:互聯網
上載者:User
iis6開啟gzip後,是先將需要壓縮的靜態檔案壓縮儲存在一個目錄,請求來時先判斷是否支援gzip,不支援直接發送靜態檔案,支援則再判斷檔案是否修改,沒有就直接發送壓縮的檔案,有則重建壓縮檔。

  根據我對公司的多個網站觀察訪問者瀏覽器支援gzip的高達99%以上,我就想又何必多儲存一份靜態檔案,直接儲存壓縮後的檔案不就ok,既節約了空間又節約了處理的過程,萬一碰見那1%不到的訪客,解個壓給他便是。好!就這麼處理,為壓縮的html專門取個尾碼名.ghtml。

  產生ghtml:

  首先iis註冊.ghtml檔案交給.net處理。

  然後將需要產生ghtml的aspx檔案通過這個函數處理,也就是產生靜態檔案,再多一步壓縮

/**///// <summary>
/// 在html目錄下產生壓縮html
/// </summary>
/// <param name="aspxPath">動態網頁面請求路徑</param>
/// <param name="urlPath">靜態頁面請求路徑</param>
public static void AspxToHtml(string aspxPath, string urlPath)
{
string filePath = HttpContext.Current.Server.MapPath(urlPath);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath.Substring(0,filePath.LastIndexOf("")));
}
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
using (GZipStream gz = new GZipStream(fs, CompressionMode.Compress))
{
using (StreamWriter sw = new StreamWriter(gz, Encoding.UTF8))
{
HttpContext.Current.Server.Execute(aspxPath, sw,false);
sw.Flush();
}
}
}
}

  處理ghtml請求,瀏覽器支援gzip就直接寫入檔案,否則先解壓內容再輸出:

  自己寫個HttpModule,在BeginRequest事件中處理.ghtml請求 ,靜態頁嘛就類比一下html的304處理

public class FreeModule : IHttpModule
{
// Init方法僅用於給期望的事件註冊方法
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}

private void SetClientCaching(HttpResponse response, DateTime lastModified)
{
response.Cache.SetETag(lastModified.Ticks.ToString());
response.Cache.SetLastModified(lastModified);
response.Cache.SetCacheability(HttpCacheability.Public);
}

// 處理BeginRequest 事件的實際代碼
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
HttpRequest request=context.Request;
HttpResponse response = context.Response;

string path = context.Request.Path.ToLower();

string acceptEncoding = request.Headers["Accept-Encoding"];

bool accept = !string.IsNullOrEmpty(acceptEncoding)? acceptEncoding.ToLower().Contains("gzip") : false;

if (path.Contains(".ghtml"))
{
string filePath = request.PhysicalApplicationPath + "/html" + path;
if (!File.Exists(filePath))
{ throw new FileNotFoundException("找不到檔案ghtml"); }

DateTime writeTime = File.GetLastWriteTimeUtc(filePath);
DateTime since;
if (DateTime.TryParse(request.Headers["IfModifiedSince"],out since) && writeTime == since.ToUniversalTime() )
{
response.StatusCode = 304;
response.StatusDescription = "Not Modified";
}
else

{

if (accept )
{

response.AppendHeader("Content-Encoding", "gzip");

response.TransmitFile(filePath);

}

else

{

response.Write(DezipText(filePath)); // 解壓ghtml檔案

}

SetClientCaching(response, writeTime);
response.End();
}
}
}
public void Dispose()
{
}
}

  解壓ghtml:

  最後還有個解壓ghtml函數

/**//// <summary>
/// 解壓text檔案後返回str
/// </summary>
/// <param name="textPath">實體路徑</param>
/// <returns>檔案字串</returns>
public static string DezipText(string textPath)
{
using (FileStream fs = File.OpenRead(textPath))
{
GZipStream gz = new GZipStream(fs, CompressionMode.Decompress);
StreamReader sr = new StreamReader(gz);
return sr.ReadToEnd();
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.