ASP.NET Routing 是獨立於 MVC/WebForms 的通用 URL 路由引擎,核心組件:
UrlRoutingModule (HttpModule):攔截請求、匹配路由RouteCollection (RouteTable.Routes):路由規則集合,執行緒安全RouteBase:抽象基類,Route 為標準實作IRouteHandler:路由處理器介面,產生 IHttpHandler<system.webServer>
<modules>
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</modules>
</system.webServer>
(IIS 7+ 整合模式;傳統模式在 `
void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
// 忽略規則必須放在最前面
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("scripts/{*pathInfo}");
routes.IgnoreRoute("images/{*pathInfo}");
// 標準 MVC 路由
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
UrlRoutingModule 監聽此事件RouteTable.Routes.GetRouteData(httpContext)RouteCollection 依序詢問每個 RouteBase.GetRouteData()RouteData 獲勝,後續規則不再評估Values:擷取的路由參數 (controller, action, id...)RouteHandler:IRouteHandler 實例,負責產生 HTTP HandlerIgnoreRoute 內部建立的 Route,其 RouteHandler 為 StopRoutingHandler。匹配成功時:
GetHttpHandler(requestContext)IHttpHandler 放入 HttpContext.ItemsHttpContext.Current.Handlerhandler.ProcessRequest()Routing 核心不綁定特定框架:
MvcRouteHandler → MvcHandler → Controller/ActionPageRouteHandler → Page HandlerDynamicDataRouteHandlerIRouteHandler + IHttpHandler