稍大型的網站都會將asp.net的頁面緩衝起來,使用者訪問時首先檢查對應的html檔案是否存在,不存在時才去產生一次。或乾脆只將asp.net作為背景程式,在背景程式產生的整站的html檔案,網站只以html的形式提供給瀏覽者。後者自成系統,效率比前者好,但比前者要複雜多了,並不是我能三語兩言能說的;我只想,前者有沒有簡便一些的asp.net程式html化的方式呢?
為一個asp.net程式添加一個HttpModule,做了一個小嘗試
<httpModules>
<add name="MyHtmlModule" type="ModuleLib.MyHtmlModule, ModuleLib" />
</httpModules>
MyHtmlModule.cs很簡單,他實現IHttpModule介面
public void Init(HttpApplication context)
{
// TODO: 添加 HtmlModule.Init 實現
context.BeginRequest+=new EventHandler(context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
switch(context.Request.Path)
{
case "/HttpModuleTest/HTMLPage.aspx?page=1":
context.RewritePath("HTMLPage_page_1.htm");
break;
case "/HttpModuleTest/HTMLPage.aspx?page=2":
context.RewritePath("HTMLPage_page_2.htm");
break;
}
}
上面的context_BeginRequest方法是很笨的,只是為了測試,實際中用Regex把aspx<=>html的命名對應起來就簡單了。
測試基本上證明想法是行得通的。測試專案中的“HTMLPage.aspx”始終沒有得到執行的機會,而2個html也如期的出現在IE上。
那麼在實際應用時,使用Regex擷取對應的HTML檔案名稱,檢測HTML是否存在,不存在,訪問aspx檔案並儲存其產生的內容。存在當然就好辦了,直接RewritePath(html)。
效率自然無法跟asp.net產生的純html網站比。