MVC路由解析---UrlRoutingModule asp.net
Area的使用ide
此文全文內容90%轉自函數
在MVC中,一個請求對應一個Controller的Action,熟悉asp.net的人應該知道,asp.net請求實際交給了HttpHandler進行了處理,HttpHandler就是ASP.NET的處理器。MVC的Action,請求都會交給HttpHandler。具體是在管道事件中,會根據請求建立一個HttpHandler,執行HttpHandler的ProcessRequest方法。ui
MVC的路由機制是經過一個UrlRoutingModule完成的,它是一個實現了IHttpModule的類,HttpModule經過註冊HttpApplication事件參與到管道處理請求中。具體是訂閱HttpApplication某個階段的事件。廢話很少說,上源碼this
public class UrlRoutingModule:IHttpModule { public RouteCollection _routeCollection; protected virtual void Init(HttpApplication application) { application.PostResolveRequestCache+=OnApplicationPostResolveRequestCache; } void OnApplicationPostResolveRequestCache(object sender,EventArgs e) { HttpApplication app=(HttpApplication)sender; HttpContextBase context=new HttpContextWrapper(app.Context); PostResolveRequestCache(context); } public virtual void PostResolveRequestCache(HttpContextBase context) { RouteData routeData=RouteCollection.GetRouteData(context); IRouteHandler routeHandler=routeData.RouteHandler; RequestContext requestContext=new RequestContext(context,routeData); context.Request.RequestContext=requestContext; IHttpHandler httpHandler=routeHandler.GetHttpHandler(requestContext); context.RemapHandler(httpHandler); } }
咱們看看UrlRoutingModule的路線圖 spa
Route.GetRouteData:.net
public override RouteData GetRouteData(HttpContextBase httpContext) { //AppRelativeCurrentExecutionFilePath:獲取應用程序的虛擬路徑,並經過對應用程序根使用波形符(~)表示法,(例:~/page.aspx)使該路徑成爲相對路徑。 //HttpRequest.PathInfo:獲取擴展名的附加信息,例:對於 URL Http://www.contoso.com/virdir/page.html/tail,PathInfo 值爲 /tail。 string requestPath=httpContext.Request.AppRelativeCurrentExecutionFilePath.SubString(2)+httpContext.Request.PathInfo; RouteValueDictionary values=_parseRoute.Match(requestPath,Defaults); RouteData routeData=new RouteData(this,RouteHanlder); foreach(var item in values) { routeData.Values.Add(item.Key,value.Value); } //DataTokens }
GetRouteData經過HttpContext來獲取路由信息,造成RouteData,將URL與Defaults的Key進行匹配,造成RouteValueDictionary ,咱們看看RouteData內部信息code
屬性:Route--->RouteData有參構造函數的參數Route
RouteHandler--->RouteData有參構造函數的參數IRouteHandler
方法:GetRouteData---->return RouteData
GetRequiredString---->string
上述的RouteHandler由Route的構造函數參數傳入, 這裏的Route來自於