萬盛學電腦網

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

ASP.NET Routing 請求處理管線深度解析

Routing 基礎架構

ASP.NET Routing 是獨立於 MVC/WebForms 的通用 URL 路由引擎,核心組件:

  • UrlRoutingModule (HttpModule):攔截請求、匹配路由
  • RouteCollection (RouteTable.Routes):路由規則集合,執行緒安全
  • RouteBase:抽象基類,Route 為標準實作
  • IRouteHandler:路由處理器介面,產生 IHttpHandler

啟用 Routing:Web.config 設定

<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+ 整合模式;傳統模式在 `` 設定)

註冊路由:Application_Start

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 }
    );
}

請求處理流程詳解

階段一:PostResolveRequestCache 事件

  1. UrlRoutingModule 監聽此事件
  2. 呼叫 RouteTable.Routes.GetRouteData(httpContext)
  3. RouteCollection 依序詢問每個 RouteBase.GetRouteData()
  4. 首個回傳非 null 的 RouteData 獲勝,後續規則不再評估

RouteData 關鍵屬性

  • Values:擷取的路由參數 (controller, action, id...)
  • RouteHandler:IRouteHandler 實例,負責產生 HTTP Handler

特殊處理器:StopRoutingHandler

IgnoreRoute 內部建立的 Route,其 RouteHandler 為 StopRoutingHandler。匹配成功時:

  • 不繼續執行後續路由規則 (不同於回傳 null 繼續匹配)
  • 請求交回預設 ASP.NET 處理管線 (.axd、靜態檔案等)

階段二:取得 IHttpHandler

  1. 若 RouteHandler ≠ StopRoutingHandler,呼叫 GetHttpHandler(requestContext)
  2. 取得 IHttpHandler 放入 HttpContext.Items

階段三:PostMapRequestHandler 事件

  1. Module 檢查 Items 中的 Handler
  2. 存在則設為 HttpContext.Current.Handler
  3. ASP.NET 管線繼續執行,最終呼叫 handler.ProcessRequest()

擴充性說明

Routing 核心不綁定特定框架:

  • MVC:MvcRouteHandler → MvcHandler → Controller/Action
  • Web Forms:PageRouteHandler → Page Handler
  • Dynamic Data:DynamicDataRouteHandler
  • 自訂框架 (如 FubuMVC):實作 IRouteHandler + IHttpHandler

關鍵設計重點

  • 順序敏感:規則由上而下匹配,通用規則放後面
  • IgnoreRoute 置頂:靜態資源、.axd 必須優先排除
  • 執行緒安全:RouteCollection 可運行時動態增刪
  • 解耦:Routing 只負責 URL ↔ 參數映射,不處理業務邏輯
copyright © 萬盛學電腦網 all rights reserved