前幾天寫了兩篇關於URL重寫時,產生靜態頁面的隨筆。
利用UrlRewrite,asp.net動態產生htm頁面
利用UrlRewrite,asp.net動態產生htm頁面(補充說明)
今天把原來的思路給整理了一下,原來需要兩個類(ModuleRewriter和CreateHtmFactoryHandler)才能完成整個過程,現在只用ModuleRewriter就可以了,我畫了個流程圖
關鍵類ModuleRewriter代碼Code
using System;
using System.Text.RegularExpressions;
using System.Configuration;
using URLRewriter.Config;
using System.Data;
using System.Web;
using System.Web.UI;
namespace URLRewriter
{
/**//// <summary>
/// Provides a rewriting HttpModule.
/// </summary>
public class ModuleRewriter : BaseModuleRewriter
{
/**//// <summary>
/// This method is called during the module's BeginRequest event.
/// </summary>
/// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
/// <param name="app">The HttpApplication instance.</param>
protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
{
//只對檔案尾碼為aspx頁面有效
if (requestedPath.IndexOf(".aspx") != -1)
{
HttpContext httpContext = app.Context;
// get the configuration rules
RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
// iterate through each rule
for (int i = 0; i < rules.Count; i++)
{
// get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
string lookFor = "^" + RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].LookFor) + "$";
// Create a regex (note that IgnoreCase is set)
Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
// See if a match is found
if (re.IsMatch(requestedPath))
{
//aspx頁面重新導向到htm頁面且http資料轉送方式為“GET”
if (rules[i].Type == WebType.Static && app.Context.Request.RequestType == "GET")
{
//靜態頁面路徑
string htmlWeb = RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].SendTo);
//靜態頁面實體路徑
string htmPath = httpContext.Server.MapPath(htmlWeb);
//靜態頁面的最後修改時間
DateTime dt = System.IO.File.GetLastWriteTime(htmPath);
if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0) //目前時間和靜態頁面產生時間對比,如果時間小於一個小時,重新導向到靜態頁面
{
requestedPath = htmlWeb;
}
else //目前時間和靜態頁面產生時間對比,如果時間大於一個小時,設定Response篩選器,用於產生靜態頁面
{
httpContext.Response.Filter = new ResponseFilter(httpContext.Response.Filter, htmPath);
}
}
else
{
requestedPath = rules[i].SendTo;
}
// Rewrite the URL
RewriterUtils.RewriteUrl(httpContext, requestedPath);
break; // exit the for loop
}
}
}
}
}
}
現在提供的原始碼是最新的,日期為2008-7-17,這次修改的地方有:
1,對Regex執行個體,做了緩衝
2,使用線程池,提高了效率
3,修改了其他一些代碼,減少了訪問頁面的等待時間
原代碼和示範樣本 下載