MVC路由之浅见
1、定义路由、路由规则
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
路由能提供什么?
● 通过路由的GetRouteData()方法,获取到封装路由信息的RouteData类型;
● 通过路由的Constraints属性获取路由约束;
......
MapRoute()是RouteCollection的扩展方法:
RouteCollection是什么?
RouteCollection是RouteBase的集合类。
2、注册路由规则
在全局文件中注册路由规则:
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ...... RouteConfig.RegisterRoutes(RouteTable.Routes); ...... } }
原来,所有的路由规则都存放在RouteTable中类型为RouteCollection的Routes属性中了。
3、UrlRoutingModule处理url请求,输出MvcHandler以处理HTTP请求
UrlRoutingModule实现IHttpModule接口,对HttpApplication的PostResolveRequest事件进行侦听:
public class UrlRoutingModule : IHttpModule { public void Init(HttpApplication context) { context.PostResolveRequestCache += OnPostResolveRequestCache; } portected virtual void OnPostResolveRequestCache(object sender, EventArgs e) { //把当前上下文封装 HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current); //获取当前请求中的RouteData类型 RouteData routeData = RouteTable.Routes.GetRouteData(httpContext); if(routeData == null) { return; } //把routeData再封装起来 RequestContext requestContext = new RequestContext{ RouteData = routeData, HttpContext = httpContext }; //从RouteData的RouteHandler属性获取IRouteHandler类型 //IRouteHandler的GetHttpHandler()方法获取IHttpHandler IHttpHandler handler = routeData.RouteHandler.GetHttpHandler(requestContext); //为当前上下文设置HttpHandler,用于对当前HTTP请求的处理 httpContext.RemapHandler(handler); } }
IRouteHandler是什么?
他的唯一职责是生产IHttpHandler实例。
public interface IRouteHandler { IHttpHandler GetHttpHandler(RequestContext requestContext); }
在MVC中默认使用的是MvcRouteHandler,是IRouteHandler的实现,返回类型为IHttpHandler的MvcHandler:
public class MvcRouteHandler : IRouteHander { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new MvcHandler(requestContext); } }
MvcHandler是MVC中IHttpHandler的默认实现:
public class MvcHandler : IHttpHandler { publci bool IsReusable{get {return false;}} public RequestContext RequestContext{get; private set;} public MvcHandler(RequestContext requestContext) { this.RequestContext = requestContext; } public void ProcessRequest(HttpContext context) { string controllerName = this.RequestContext.RouteData.Controller; IControllerFactory controllerFactory = COntrollerBuilder.Current.GetControllerFactory(); IController controller = controllerFactory.CreateController(this.RequestContext, controllerName); controller.execute(this.RequestContext); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。