从一个针对ASP.NET MVC框架的Controller.Action的请求处理顺序来说整个请求过程。

本文详细介绍了ASP.NET MVC中路由模块的工作原理,包括UrlRoutingModule如何注册事件、RouteCollection如何按顺序调用各Route对象的GetRouteData方法来匹配请求路径,并最终获取RouteData的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    下面引用的所有代码都来自ASP.NET MVC的源码,但是可能只选取每个方法的其中一部分。

    System.Web.Routing.UrlRoutingModule在管道事件中注册PostResolveRequestCache事件。

protected virtual void Init(HttpApplication application) {
    application.PostResolveRequestCache += OnApplicationPostResolveRequestCache;
}

  在这个事件中会调用RouteCollection.GetRouteData方法去获取RoteData,而RouteCollection.GetRouteData方法会按照Route对象注册的顺序先后调用在web应用程序中注册的所有Route对象的GetRouteData方法,在调用过程中如果发现有一个匹配的,那么后续的Route对象的GetRouteData方法不会再执行(所以最特殊的Route需要最先注册,避免被通用的Route先匹配上)。

public RouteData GetRouteData(HttpContextBase httpContext) {
	// Go through all the configured routes and find the first one that returns a match
	using (GetReadLock()) {
		foreach (RouteBase route in this) {
			RouteData routeData = route.GetRouteData(httpContext);
			if (routeData != null) {
				// If we're not routing existing files on this route and the file exists, we also stop processing routes
				if (!route.RouteExistingFiles) {
					if (!doneRouteCheck) {
						isRouteToExistingFile = IsRouteToExistingFile(httpContext);
						doneRouteCheck = true;
					}
					if (isRouteToExistingFile) {
						return null;
					}
				}
				return routeData;
			}
		}
	}
	return null;
}

  在管道事件PostResolveRequestCache中获取到RouteData对象之后,会通过该对象的RouteHandler属性去获取一个

 

转载于:https://www.cnblogs.com/swyy/p/5114248.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值