在 ASP.NET Web Forms 時代,若需將動態網址(如 product.aspx?id=123)轉為靜態化路徑(/product/123),常於 Global.asax 的 Application_BeginRequest 事件中攔截並重寫路徑。本文解析一段經典的 URL Rewrite 實作碼,並說明其運作原理與現代替代方案。
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string strCurrentPath = Request.Path;
// 僅處理 .aspx 請求,略過圖片、WebResource.axd 等靜態資源
if (Path.GetExtension(strCurrentPath).EndsWith("aspx", true, CultureInfo.InvariantCulture))
{
string qString = Request.QueryString.ToString();
if (!string.IsNullOrEmpty(qString)) qString = "&" + qString;
strCurrentPath = strCurrentPath.ToLowerInvariant();
string appRoot = GetAppRoot(strCurrentPath);
// 目錄映射規則:/catalog/xxx.aspx → catalog.aspx?guid=xxx
if (strCurrentPath.IndexOf("catalog/", StringComparison.InvariantCultureIgnoreCase) > -1)
{
appRoot = appRoot.Replace("catalog/", "");
string strCustomPath = appRoot + "catalog.aspx?guid=" +
Path.GetFileNameWithoutExtension(strCurrentPath) + qString;
Context.RewritePath(strCustomPath, false);
}
// 目錄映射規則:/product/xxx.aspx → product.aspx?guid=xxx
else if (strCurrentPath.IndexOf("product/", StringComparison.InvariantCultureIgnoreCase) > -1)
{
appRoot = appRoot.Replace("product/", "");
string strCustomPath = appRoot + "product.aspx?guid=" +
Path.GetFileNameWithoutExtension(strCurrentPath) + qString;
Context.RewritePath(strCustomPath, false);
}
}
}
| 優點 | 缺點 |
|---|---|
| 無需額外元件,純 ASP.NET 實作 | 邏輯硬寫在 Global.asax,維護困難 |
| 效能開銷極低 | 規則擴充需修改程式碼並重新編譯 |
| 相容舊版 ASP.NET (2.0+) | 缺乏規則引擎,不支援正則、條件判斷等進階功能 |
RouteTable.Routes.MapPageRoute 宣告式配置,支援參數約束、預設值。app.UseRewriter() 或 app.MapWhen(),跨平台、高效能。舊專案若仍在維護模式,可保留現有機制;新專案或重構時,強烈建議採用 ASP.NET Routing 或 IIS URL Rewrite Module,獲得更佳的可維護性、測試性與擴充性。