萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Global.asax 與 URL Rewrite:Application_BeginRequest 實作友善網址

URL 重寫:從醜陋 QueryString 到乾淨 RESTful 風格

利用 `Global.asax` 的 `Application_BeginRequest` 事件攔截所有請求,配合 RegEx 解析友善網址,內部 `Context.RewritePath` 轉發至真實處理頁面,瀏覽器網址列保持不變。

Global.asax 核心程式碼

protected void Application_BeginRequest(object sender, EventArgs e)
{
    // 僅處理 .aspx 動態頁面,靜態檔案由 IIS 直接服務不經此事件
    var path = Context.Request.Path;
    
    // 比對模式:/ViewPerson-123.aspx → /ViewPerson.aspx?id=123
    var match = Regex.Match(path, @"^/ViewPerson-(\d+)\.aspx$", RegexOptions.IgnoreCase);
    if (match.Success)
    {
        string id = match.Groups[1].Value;
        Context.RewritePath("/ViewPerson.aspx?id=" + id);
    }
    
    // 可擴充更多規則
    // match = Regex.Match(path, @"^/Product/(\d+)/(.+)\.html$");
    // if (match.Success) Context.RewritePath("/Product.aspx?id=" + match.Groups[1].Value);
}

關鍵點解析

  • Application_BeginRequest:每個請求最先觸發的事件 (靜態檔案除外),適合 URL Rewrite、權限檢查、記錄日誌。
  • Context.RewritePath:內部伺服器端轉發,**瀏覽器網址不變**,不同於 `Response.Redirect` (302 導向、網址改變)。
  • Regex 擷取群組:`(\d+)` 捕獲數字 ID,`Groups[1]` 取得。
  • 靜態檔案不經此管線:`.jpg/.css/.js` 由 IIS 靜態檔案處理器直接服務,不觸發 ASP.NET 管線 (除非設定 `runAllManagedModulesForAllRequests="true"`)。

進階:UrlRewriteModule / IIS URL Rewrite Module

生產環境建議使用 **IIS 原生 URL Rewrite Module** (web.config 設定),效能更好、支援輸出重寫、SEO 友善:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="PersonFriendlyUrl" stopProcessing="true">
        <match url="^ViewPerson-([0-9]+)\.aspx$" />
        <action type="Rewrite" url="ViewPerson.aspx?id={R:1}" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

比較:Global.asax Rewrite vs IIS Rewrite Module

特性Global.asax (Managed)IIS URL Rewrite (Native)
效能較低 (Managed 管線)極高 (Kernel 模式)
靜態檔案處理需額外設定原生支援
輸出重寫 (Response Filter)困難支援 `outboundRules`
部署僅需程式碼需安裝模組、web.config
除錯Visual Studio 斷點Failed Request Tracing

建議: 新專案直接用 IIS URL Rewrite Module;舊專案快速修補可用 Global.asax;ASP.NET Core 使用 `app.UseRewriter()` Middleware 或 `MapWhen`/`Map` 自訂 Middleware。

copyright © 萬盛學電腦網 all rights reserved