Global.asax(ASP.NET 應用程式檔案)提供應用程式層級與模組層級事件的集中處理點,是實作横切關注點的關鍵位置。
| 事件 | 觸發時機 | 典型用途 |
|---|---|---|
Application_Start | 網站首次被存取(服務啟動後) | 初始化快取、註冊路由、啟動背景服務 |
Application_Error | 發生未處理例外 | 全域錯誤記錄、友善錯誤頁面導向 |
Session_End | InProc 模式下 Session 結束 | 清理使用者資源、記錄離線時間 |
Application_BeginRequest | 每個請求進入管線開始 | URL Rewrite、權限攔截、多語系解析 |
Application_BeginRequest,由 IIS 直接服務Application_BeginRequest// 醜陋網址 - 參數外露、不利 SEO https://localhost/viewPerson.aspx?id=1 // 美觀網址 - 語意化、SEO 友善、易記憶 https://localhost/viewPerson-1.aspx
利用 Application_BeginRequest 攔截所有動態請求,透過 Regular Expression 比對美觀網址模式,內部重寫至真實處理頁面。
protected void Application_BeginRequest(object sender, EventArgs e)
{
// 比對模式:/ViewPerson-{數字}.aspx
Match match = Regex.Match(Context.Request.Path, @"^/ViewPerson\-(\d+)\.aspx$");
if (match.Success)
{
// 擷取捕獲群組:(\d+) 即為 id 值
string id = match.Groups[1].Value;
// 內部重寫:瀏覽器網址列不變,伺服器內部轉交處理
Context.RewritePath("/ViewPerson.aspx?id=" + id);
}
}
| 特性 | Context.RewritePath | Response.Redirect |
|---|---|---|
| 瀏覽器網址列 | 不變 | 改變 |
| HTTP 狀態碼 | 200 | 302 |
| 搜尋引擎視角 | 單一 URL | 兩個 URL |
| 效能 | 伺服器內部轉交 | 雙倍請求 |
| 適用場景 | URL Rewrite、內部路由 | 登入導向、跨域跳轉 |
^/ViewPerson\-(\d+)\.aspx$ ^ 字串開頭 /ViewPerson 字面匹配 \- 跳脫字元:連字號 (\d+) 捕獲群組:一個以上數字 \.aspx 字面匹配:.aspx $ 字串結尾
protected void Application_BeginRequest(object sender, EventArgs e)
{
var routes = new Dictionary
{
{ @"^/Product\-(\d+)\.aspx$", "/ProductDetail.aspx?id=$1" },
{ @"^/Category\-(\w+)\.aspx$", "/CategoryList.aspx?name=$1" },
{ @"^/Article\-(\d+)\-(\d+)\.aspx$", "/Article.aspx?cat=$1&id=$2" }
};
string path = Context.Request.Path;
foreach (var route in routes)
{
Match match = Regex.Match(path, route.Key);
if (match.Success)
{
string target = route.Value;
for (int i = 1; i <= match.Groups.Count - 1; i++)
{
target = target.Replace("$" + i, match.Groups[i].Value);
}
Context.RewritePath(target);
break;
}
}
}
System.Web.Routing,Web Forms 4.0+ 內建支援Global.asax 配合 Application_BeginRequest 實作 URL Rewrite,是 Web Forms 時代打造美觀網址的經典技法,理解其原理有助於遷移至現代路由系統時的架構決策。