解決這個(gè)問(wèn)題,我們需要先了解ASP.NET應(yīng)用程序的生命周期,先看下面作者整理的一張圖片:
從圖中我們可以清楚的看到:通用IIS訪問(wèn)應(yīng)用程序時(shí),每次的單個(gè)頁(yè)面URL訪問(wèn)時(shí),都會(huì)先經(jīng)過(guò)HttpApplication 管線處理請(qǐng)求,走過(guò)BeginRequest 事件之后才會(huì)去走路由訪問(wèn)具體的Controller和Action,最后結(jié)束的時(shí)候會(huì)請(qǐng)求EndRequest事件。下面用一張圖來(lái)表示這個(gè)順序:
注意圖中標(biāo)示的紅色部分就是我們要實(shí)現(xiàn)的部分,實(shí)現(xiàn)如下:
1 新建MyHandler.cs
public class MyHandler:IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
application.EndRequest +=
(new EventHandler(this.Application_EndRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".html"))
{
context.Response.WriteFile(context.Server.MapPath(filePath));//直接走靜態(tài)頁(yè)面
//此處可以加入緩存,條件也可以根據(jù)需要來(lái)自己定義
context.Response.End();
}
}
private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".html"))
{
context.Response.Write("<hr><h1><font color=red>" +
"HelloWorldModule: End of Request</font></h1>");
}
}
public void Dispose() { }
}
2. web.config中加入以下代碼,才會(huì)運(yùn)行自定義的管道處理類(lèi)
<httpModules>
<add name="MvcTest.MyHandler" type="MvcTest.MyHandler"/>
</httpModules>
運(yùn)行一下自己的代碼,看看效果你就全明白了!
補(bǔ)充:根據(jù)@小尾魚(yú)的提示,如果直接在自己的項(xiàng)目文件下生產(chǎn)了和URL中一樣的目錄文件,比如訪問(wèn):yourdomin.com/product/1.html,你的項(xiàng)目文件夾下真的存在product/1.html這個(gè)路徑,那么IIS會(huì)直接去請(qǐng)求這個(gè)靜態(tài)頁(yè)面,如果項(xiàng)目中使用了自定義的管道處理程序,那么這個(gè)靜態(tài)頁(yè)仍然會(huì)走我們的自定義管道處理程序,我們可以在這里通過(guò)緩存來(lái)實(shí)現(xiàn)要不要重新成長(zhǎng)靜態(tài)頁(yè)或刪除過(guò)期產(chǎn)品的靜態(tài)頁(yè),如果不使用此方法,只能去寫(xiě)執(zhí)行計(jì)劃,定時(shí)跑這些靜態(tài)文件了,修改Application_BeginRequest
private void Application_BeginRequest(Object source,
EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".html"))
{
//判斷緩存是否存在,不存在加入緩存,調(diào)用生成靜態(tài)的類(lèi)和方法
//產(chǎn)品過(guò)期,移除靜態(tài)文件,302重定向
if (System.IO.File.Exists(context.Server.MapPath(filePath)))
{
context.Response.WriteFile(context.Server.MapPath(filePath));
context.Response.End();
}
}
思路大體如此。