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

    下面引用的所有代码都来自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