首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 路由系統核心原理:HttpHandler 動態映射機制

     編輯:關於ASP.NET

ASP.NET 中每個請求最終皆由具體的 HttpHandler 處理,熟悉的 Page 物件即是一種 HttpHandler,負責處理 .aspx 檔案請求。透過 HttpHandler 的動態映射,可實現請求網址與實體檔案路徑的分離,這正是 ASP.NET 路由系統的核心實作原理。

路由系統架構

ASP.NET 路由系統透過一個註冊至應用程式的自訂 HttpModule(UrlRoutingModule)攔截所有請求,分析後動態匹配對應的 HttpHandler 進行處理,最後將結果寫入 HTTP 回應。

路由系統架構圖

UrlRoutingModule 攔截機制

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

PageRouteHandler 與 MvcRouteHandler

路由對象的 RouteHandler 決定最終的處理器:

  • PageRouteHandler:對應 MapPageRoute 註冊的路由,最終建立 Page 物件處理 .aspx 頁面。
  • MvcRouteHandler:對應 MapRoute 註冊的 MVC 路由,回傳 MvcHandler,由其負責 Controller 啟動、Action 執行及回應處理,是 MVC 框架的核心執行器。
public class MvcRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MvcHandler(requestContext);
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved