zoukankan      html  css  js  c++  java
  • Asp.Net MVC的路由

      通过前面几篇博文的介绍,现在我们已经清楚了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
    /// <summary>Maps the specified URL route and sets default route values, constraints, and namespaces.</summary>
    /// <returns>A reference to the mapped route.</returns>
    /// <param name="routes">A collection of routes for the application.</param>
    /// <param name="name">The name of the route to map.</param>
    /// <param name="url">The URL pattern for the route.</param>
    /// <param name="defaults">An object that contains default route values.</param>
    /// <param name="constraints">A set of expressions that specify values for the <paramref name="url" /> parameter.</param>
    /// <param name="namespaces">A set of namespaces for the application.</param>
    /// <exception cref="T:System.ArgumentNullException">The <paramref name="routes" /> or <paramref name="url" /> parameter is null.</exception>
    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;
    }
    using System;
    using System.Web.Mvc.Properties;
    using System.Web.Routing;
    using System.Web.SessionState;
    namespace System.Web.Mvc
    {
        /// <summary>Creates an object that implements the IHttpHandler interface and passes the request context to it.</summary>
        public class MvcRouteHandler : IRouteHandler
        {
            private IControllerFactory _controllerFactory;
            /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class.</summary>
            public MvcRouteHandler()
            {
            }
            /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class using the specified factory controller object.</summary>
            /// <param name="controllerFactory">The controller factory.</param>
            public MvcRouteHandler(IControllerFactory controllerFactory)
            {
                this._controllerFactory = controllerFactory;
            }
            /// <summary>Returns the HTTP handler by using the specified HTTP context.</summary>
            /// <returns>The HTTP handler.</returns>
            /// <param name="requestContext">The request context.</param>
            protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
            {
                requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext));
                return new MvcHandler(requestContext);
            }
            /// <summary>Returns the session behavior.</summary>
            /// <returns>The session behavior.</returns>
            /// <param name="requestContext">The request context.</param>
            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
    {
        /// <summary>Matches a URL request to a defined route.</summary>
        [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;
            /// <summary>Gets or sets the collection of defined routes for the ASP.NET application.</summary>
            /// <returns>An object that contains the routes.</returns>
            public RouteCollection RouteCollection
            {
                get
                {
                    if (this._routeCollection == null)
                    {
                        this._routeCollection = RouteTable.Routes;
                    }
                    return this._routeCollection;
                }
                set
                {
                    this._routeCollection = value;
                }
            }
            /// <summary>Disposes of the resources (other than memory) that are used by the module.</summary>
            protected virtual void Dispose()
            {
            }
            /// <summary>Initializes a module and prepares it to handle requests.</summary>
            /// <param name="application">An object that provides access to the methods, properties, and events common to all application objects in an ASP.NET application.</param>
            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);
            }
            /// <summary>Assigns the HTTP handler for the current request to the context.</summary>
            /// <param name="context">Encapsulates all HTTP-specific information about an individual HTTP request.</param>
            /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Web.Routing.RouteData.RouteHandler" /> property for the route is null.</exception>
            [Obsolete("This method is obsolete. Override the Init method to use the PostMapRequestHandler event.")]
            public virtual void PostMapRequestHandler(HttpContextBase context)
            {
            }
            /// <summary>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.</summary>
            /// <param name="context">Encapsulates all HTTP-specific information about an individual HTTP request.</param>
            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,这种扩展可以随意的定制规则,而不仅仅是表达式

        /// <summary>
        /// 直接扩展route
        /// </summary>
        public class MyRoute : RouteBase
        {
            /// <summary>
            /// 解析路由信息
            /// </summary>
            /// <param name="httpContext"></param>
            /// <returns></returns>
            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; } /// <summary> /// 指定处理的虚拟路径 /// </summary> /// <param name="requestContext"></param> /// <param name="values"></param> /// <returns></returns> 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

        /// <summary>
        /// 扩展IRouteHandler /// </summary>
        public class MyRouteHandler : IRouteHandler
        {
            public IHttpHandler GetHttpHandler(RequestContext requestContext)
            {
                return new MyHttpHandler(requestContext);
            }
        }
    
        /// <summary>
        /// 扩展IHttpHandler
        /// </summary>
        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);

    运行看结果

  • 相关阅读:
    分页工具类
    ajax乱码的问题
    ibatis配置文件中的XML解析错误The content of elements must consist of well-formed character data or markup.
    nginx 反向代理导致的session丢失的问题
    后台返回的值ajax接收不到
    C/C++中vector与list的区别
    C/C++中内存泄漏、内存溢出与野指针的解释与说明
    C++中深拷贝与浅拷贝
    C++中的构造函数与析构函数及组合类的调用
    Linux中request_irq()中断申请与处理说明
  • 原文地址:https://www.cnblogs.com/jesen1315/p/11003851.html
Copyright © 2011-2022 走看看