利用 `Global.asax` 的 `Application_BeginRequest` 事件攔截所有請求,配合 RegEx 解析友善網址,內部 `Context.RewritePath` 轉發至真實處理頁面,瀏覽器網址列保持不變。
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);
}
生產環境建議使用 **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 (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。