软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > 网络编程 > ASP.NET > ASP.NET MVC 1.0 流程分析(System.Web.Routing)

ASP.NET MVC 1.0 流程分析(System.Web.Routing)

MVC 依赖 System.Web.Routing 处理请求路径解析,也就是说整个流程的起始是由 System.Web.Routing.UrlRoutingModule 开始的。

Web.config
<httpModules>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, ..."/>
</httpModules>

那么我们就看看这个 UrlRoutingModule 内部都做了什么。

public class UrlRoutingModule : IHttpModule
{
protected virtual void Init(HttpApplication application)
{
application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);
application.PostMapRequestHandler += new EventHandler(this.OnApplicationPostMapRequestHandler);
}
}

订阅了两个 HttpApplication 事件。在 ASP.NET 应用程序生命周期中 PostResolveRequestCache 会在 PostMapRequestHandler 之前触发,最后是 IHttpHandler.ProcessRequest() 完成最终的请求处理。

通过对请求上下文进行包装,进一步进行处理。

public class UrlRoutingModule : IHttpModule
{
private void OnApplicationPostMapRequestHandler(object sender, EventArgs e)
{
HttpContextBase context = new HttpContextWrapper(((HttpApplication) sender).Context);
this.PostMapRequestHandler(context);
}

private void OnApplicationPostResolveRequestCache(object sender, EventArgs e)
{
HttpContextBase context = new HttpContextWrapper(((HttpApplication) sender).Context);
this.PostResolveRequestCache(context);
}
}

首先, PostResolveRequestCache 被执行。

public class UrlRoutingModule : IHttpModule
{
public virtual void PostResolveRequestCache(HttpContextBase context)
{
RouteData routeData = this.RouteCollection.GetRouteData(context);

if (routeData != null)
{
IRouteHandler routeHandler = routeData.RouteHandler;

...

if (!(routeHandler is StopRoutingHandler))
{
RequestContext requestContext = new RequestContext(context, routeData);
IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);

...

RequestData data2 = new RequestData();
data2.OriginalPath = context.Request.Path;
data2.HttpHandler = httpHandler;
context.Items[_requestDataKey] = data2;
context.RewritePath("~/UrlRouting.axd");
}
}
}
}

RouteCollection 实际是对 RouteTable.Routes 的引用。

public class UrlRoutingModule : IHttpModule
{
public RouteCollection RouteCollection
{
get
{
if (this._routeCollection == null)
{
this._routeCollection = RouteTable.Routes;
}
return this._routeCollection;
}
set
{
this._routeCollection = value;
}
}
}

好吗,又跳了一回。

public class RouteTable
{
private static RouteCollection _instance = new RouteCollection();

public static RouteCollection Routes
{
get
{
return _instance;
}
}
}

相关阅读
网友评论
栏目导航
推荐软件