ASP.NET 中每個請求最終皆由具體的 HttpHandler 處理,熟悉的 Page 物件即是一種 HttpHandler,負責處理 .aspx 檔案請求。透過 HttpHandler 的動態映射,可實現請求網址與實體檔案路徑的分離,這正是 ASP.NET 路由系統的核心實作原理。
ASP.NET 路由系統透過一個註冊至應用程式的自訂 HttpModule(UrlRoutingModule)攔截所有請求,分析後動態匹配對應的 HttpHandler 進行處理,最後將結果寫入 HTTP 回應。

UrlRoutingModule 透過註冊 HttpApplication 的 PostResolveRequestCache 事件來攔截請求:
public class UrlRoutingModule : IHttpModule
{
public RouteCollection RouteCollection { get; set; }
public void Init(HttpApplication context)
{
context.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);
}
private void OnApplicationPostResolveRequestCache(object sender, EventArgs e);
}
其核心邏輯在 OnApplicationPostResolveRequestCache 方法中:取得 HTTP 上下文,呼叫 RouteCollection.GetRouteData 獲得 RouteData,再透過 RouteHandler 取得 HttpHandler,最後以 RemapHandler 完成映射。
private void OnApplicationPostResolveRequestCache(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
HttpContextBase contextWrapper = new HttpContextWrapper(context);
RouteData routeData = this.RouteCollection.GetRouteData(contextWrapper);
RequestContext requestContext = new RequestContext(contextWrapper, routeData);
IHttpHandler handler = routeData.RouteHandler.GetHttpHandler(requestContext);
context.RemapHandler(handler);
}
路由對象的 RouteHandler 決定最終的處理器:
MapPageRoute 註冊的路由,最終建立 Page 物件處理 .aspx 頁面。MapRoute 註冊的 MVC 路由,回傳 MvcHandler,由其負責 Controller 啟動、Action 執行及回應處理,是 MVC 框架的核心執行器。public class MvcRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MvcHandler(requestContext);
}
}