首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 全域攔截重寫 URL:實現靜態化路由映射

     編輯:關於ASP.NET

在 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);
        }
    }
}

關鍵技術點

  1. Application_BeginRequest:管線最早期攔截點,所有請求必經此處。
  2. Context.RewritePath:伺服器端內部轉向,瀏覽器網址列不變,保持 SEO 友善。
  3. 路徑解析邏輯:提取目錄名(catalog/product)與檔名(作為 GUID 參數),組合成目標 .aspx 頁面與查詢字串。
  4. 副檔名過濾:僅處理 .aspx,避免影響靜態資源與 AXD 處理器效能。

優缺點評析

優點缺點
無需額外元件,純 ASP.NET 實作邏輯硬寫在 Global.asax,維護困難
效能開銷極低規則擴充需修改程式碼並重新編譯
相容舊版 ASP.NET (2.0+)缺乏規則引擎,不支援正則、條件判斷等進階功能

現代替代方案

  • ASP.NET Routing (3.5 SP1+):RouteTable.Routes.MapPageRoute 宣告式配置,支援參數約束、預設值。
  • URL Rewrite Module (IIS 7+):Web.config 宣告式規則,支援正則、重導、快取、SEO 最佳化,脫離應用程式碼。
  • ASP.NET Core Middleware:app.UseRewriter() 或 app.MapWhen(),跨平台、高效能。

遷移建議

舊專案若仍在維護模式,可保留現有機制;新專案或重構時,強烈建議採用 ASP.NET Routing 或 IIS URL Rewrite Module,獲得更佳的可維護性、測試性與擴充性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved