通过前面几篇博文的介绍,现在我们已经清楚了asp.net请求管道是怎么一回事了,这篇博文来聊聊MVC的路由。
其实MVC的请求管道和Asp.Net请求管道一样,只是MVC扩展了UrlRoutingModule的动作。我们知道MVC网站启动后第一个请求会执行Global.asax文件中的Application_Start方法,完成一些初始化工作,其中就会注册路由,先来看下面一张图,该图可以直观的展示了MVC执行的流程。
结合上图,我们一起来看看代码是如何实现路由的注册的。
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } public class RouteConfig { 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 } ); } }
RouteCollection通过MapRoute扩展方法拿着Url来创建Route并注册到RouteCollection其中,这一点我们通过源码可以看到该方法是如何操作的,该方法通过new一个MvcRouteHandler来创建Route。MvcRouteHandler创建了MvcHandler。紧接着继续往下执行,创建HttpApplication实例,执行后续事件,在PostResolveRequestCache事件去注册UrlRouteModule的动作。
// System.Web.Mvc.RouteCollectionExtensions///Maps the specified URL route and sets default route values, constraints, and namespaces. ///A reference to the mapped route. /// A collection of routes for the application./// The name of the route to map./// The URL pattern for the route./// An object that contains default route values./// A set of expressions that specify values for theparameter./// A set of namespaces for the application./// The public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces){ if (routes == null) { throw new ArgumentNullException("routes"); } if (url == null) { throw new ArgumentNullException("url"); } Route route = new Route(url, new MvcRouteHandler()) { Defaults = RouteCollectionExtensions.CreateRouteValueDictionaryUncached(defaults), Constraints = RouteCollectionExtensions.CreateRouteValueDictionaryUncached(constraints), DataTokens = new RouteValueDictionary() }; ConstraintValidation.Validate(route); if (namespaces != null && namespaces.Length > 0) { route.DataTokens["Namespaces"] = namespaces; } routes.Add(name, route); return route;}or parameter is null.
using System;using System.Web.Mvc.Properties;using System.Web.Routing;using System.Web.SessionState;namespace System.Web.Mvc{ ///Creates an object that implements the IHttpHandler interface and passes the request context to it. public class MvcRouteHandler : IRouteHandler { private IControllerFactory _controllerFactory; ///Initializes a new instance of the public MvcRouteHandler() { } ///class. Initializes a new instance of the /// The controller factory. public MvcRouteHandler(IControllerFactory controllerFactory) { this._controllerFactory = controllerFactory; } ///class using the specified factory controller object. Returns the HTTP handler by using the specified HTTP context. ///The HTTP handler. /// The request context. protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext) { requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext)); return new MvcHandler(requestContext); } ///Returns the session behavior. ///The session behavior. /// The request context. protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext) { string text = (string)requestContext.RouteData.Values["controller"]; if (string.IsNullOrWhiteSpace(text)) { throw new InvalidOperationException(MvcResources.MvcRouteHandler_RouteValuesHasNoController); } IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory(); return controllerFactory.GetControllerSessionBehavior(requestContext, text); } IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { return this.GetHttpHandler(requestContext); } }}
using System;using System.Globalization;using System.Runtime.CompilerServices;using System.Web.Security;namespace System.Web.Routing{ ///Matches a URL request to a defined route. [TypeForwardedFrom("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public class UrlRoutingModule : IHttpModule { private static readonly object _contextKey = new object(); private static readonly object _requestDataKey = new object(); private RouteCollection _routeCollection; ///Gets or sets the collection of defined routes for the ASP.NET application. ///An object that contains the routes. public RouteCollection RouteCollection { get { if (this._routeCollection == null) { this._routeCollection = RouteTable.Routes; } return this._routeCollection; } set { this._routeCollection = value; } } ///Disposes of the resources (other than memory) that are used by the module. protected virtual void Dispose() { } ///Initializes a module and prepares it to handle requests. /// An object that provides access to the methods, properties, and events common to all application objects in an ASP.NET application. protected virtual void Init(HttpApplication application) { if (application.Context.Items[UrlRoutingModule._contextKey] != null) { return; } application.Context.Items[UrlRoutingModule._contextKey] = UrlRoutingModule._contextKey; application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache); } private void OnApplicationPostResolveRequestCache(object sender, EventArgs e) { HttpApplication httpApplication = (HttpApplication)sender; HttpContextBase context = new HttpContextWrapper(httpApplication.Context); this.PostResolveRequestCache(context); } ///Assigns the HTTP handler for the current request to the context. /// Encapsulates all HTTP-specific information about an individual HTTP request. ///The [Obsolete("This method is obsolete. Override the Init method to use the PostMapRequestHandler event.")] public virtual void PostMapRequestHandler(HttpContextBase context) { } ///property for the route is null. Matches the HTTP request to a route, retrieves the handler for that route, and sets the handler as the HTTP handler for the current request. /// Encapsulates all HTTP-specific information about an individual HTTP request. public virtual void PostResolveRequestCache(HttpContextBase context) { RouteData routeData = this.RouteCollection.GetRouteData(context); if (routeData == null) { return; } IRouteHandler routeHandler = routeData.RouteHandler; if (routeHandler == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString("UrlRoutingModule_NoRouteHandler"), new object[0])); } if (routeHandler is StopRoutingHandler) { return; } RequestContext requestContext = new RequestContext(context, routeData); context.Request.RequestContext = requestContext; IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext); if (httpHandler == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("UrlRoutingModule_NoHttpHandler"), new object[] { routeHandler.GetType() })); } if (!(httpHandler is UrlAuthFailureHandler)) { context.RemapHandler(httpHandler); return; } if (FormsAuthenticationModule.FormsAuthRequired) { UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this); return; } throw new HttpException(401, SR.GetString("Assess_Denied_Description3")); } void IHttpModule.Dispose() { this.Dispose(); } void IHttpModule.Init(HttpApplication application) { this.Init(application); } }}
到此,路由的注册动作也就告一段落。那么在理解了MVC的路由后,可以做什么呢?我们可以对路由做一些我们自己的扩展。
可以从三个层面来扩展路由:
一、在MapRoute范围内进行扩展,这种扩展只是在扩展正则表达式
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");//忽略路由 //mvc路由规则下的扩展 routes.IgnoreRoute("Handler/{*pathInfo}"); routes.MapRoute( name: "About", url: "about",//不区分大小写 defaults: new { controller = "First", action = "String", id = UrlParameter.Optional } );//静态路由 routes.MapRoute("TestStatic", "Test/{action}", new { controller = "Second" });//替换控制器 routes.MapRoute( "Regex", "{controller}/{action}_{Year}_{Month}_{Day}", new { controller = "First", id = UrlParameter.Optional }, new { Year = @"^\d{4}", Month = @"\d{2}", Day = @"\d{2}" } );//正则路由 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new string[] { "Jesen.Web.Controllers" } ); }
二、通过继承RouteBase来扩展Route,这种扩展可以随意的定制规则,而不仅仅是表达式
////// 直接扩展route /// public class MyRoute : RouteBase { ////// 解析路由信息 /// /// ///public override RouteData GetRouteData(HttpContextBase httpContext) { //此处可以根据自己的需求做一些路由的配置,例如拒绝某个浏览器的访问,检测到Chrome浏览器,则直接跳转到某个url if (httpContext.Request.UserAgent.IndexOf("Chrome/69.0.3497.92") >= 0) { RouteData rd = new RouteData(this, new MvcRouteHandler()); rd.Values.Add("controller", "Pipe"); rd.Values.Add("action", "Refuse"); return rd; } return null; } /// /// 指定处理的虚拟路径 /// /// /// ///public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return null; } }
接着在RouteConfig和Global.asax中注册该路由
public static void RegisterMyRoutes(RouteCollection routes){ routes.Add(new MyRoute());}protected void Application_Start(){ RouteConfig.RegisterMyRoutes(RouteTable.Routes);}
三、扩展Handler,不一定是MvcHandler,可以是我们熟悉的IHttpHandler
////// 扩展IRouteHandler /// public class MyRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new MyHttpHandler(requestContext); } } ////// 扩展IHttpHandler /// public class MyHttpHandler : IHttpHandler { public MyHttpHandler(RequestContext requestContext) { } public void ProcessRequest(HttpContext context) { string url = context.Request.Url.AbsoluteUri; context.Response.Write((string.Format("当前地址为:{0}", url))); context.Response.End(); } public virtual bool IsReusable { get { return false; } } }
RouteConfig.cs文件中配置路由
public static void RegisterMyMVCHandler(RouteCollection routes) { routes.Add(new Route("MyMVC/{*Info}", new MyRouteHandler())); }
Global中注册路由
RouteConfig.RegisterMyMVCHandler(RouteTable.Routes);
运行看结果