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);

运行看结果

原文地址:https://www.cnblogs.com/jesen1315/p/11003851.html

时间: 2024-08-13 16:19:49

Asp.Net MVC的路由的相关文章

[学习笔记] 理解ASP.NET MVC的路由系统

引言 路由,正如其名,是决定消息经由何处被传递到何处的过程.也正如网络设备路由器Router一样,ASP.NET MVC框架处理请求URL的方式,同样依赖于一张预定义的路由表.以该路由表为转发依据,请求URL最终被传递给特定Controller的特定Action进行处理.而在相反的方向上,MVC框架的渲染器同样要利用这张路由表,生成最终的HTML页面并返回URL.所以,理解整个ASP.NET MVC的路由系统,有两个必须出现的关键元素:Controller与Action,有两个方向的操作:传入的

asp.net MVC 5 路由 Routing

ASP.NET MVC ,一个适用于WEB应用程序的经典模型 model-view-controller 模式.相对于web forms一个单一的整块,asp.net mvc是由连接在一起的各种代码层所组成. 最近又接触了关于asp.net mvc的项目,又重拾以前的记忆,感觉忘了好多,特此记录. 首先,来说说路由Routing. ASP.NET MVC 不再是要依赖于物理页面了,你可以使用自己的语法自定义URL,通过这些语法来指定资源和操作.语法通过URL模式集合表达,也称为路由. 路由是代表

asp.net mvc 伪静态路由配置

asp.net mvc实现伪静态路由必须按如下方式设置好,才能访问 .htm 或者.html页面 C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll 来自为知笔记(Wiz)

ASP.NET MVC API 路由生成规则

我们都知道调用ASP.NET MVC的某些API函数(诸如:Url.Action.RedirectToAction等)可以生成URL,ASP.NET MVC会根据调用API函数时传入的参数去匹配系统定义的路由(Route),然后通过匹配成功的路由去生成相应的URL. ASP.NET MVC会依次根据如下三个规则生成URL: 调用ASP.NET MVC API函数时传入的参数信息 当前请求的URL(就是Request.Url)和系统中定义路由匹配(按照路由表定义的顺序,从上往下匹配)后的匹配值 系

ASP.NET MVC——URL路由

在MVC之前,ASP.NET假设请求的URL与服务器上的文件之间有关联,服务器接受请求,并输出相应的文件.而在引入MVC后,请求是由控制器的动作方法来处理的.为了处理URL,便引入了路由系统. 首先我们来创建一个基础项目用来演示.代码如下: 1 public class HomeController : Controller 2 { 3 public ActionResult Index() 4 { 5 ViewBag.Controller = "Home"; 6 ViewBag.Ac

ASP.NET MVC之路由深究

MVC的强大之处之一当然是路由,这是几年前一位牛人给我说过的话,本人深感认同.今天就再次探究. 首先新建一个空的MVC项目,我们会发现在RouteConfig类中存在一个默认的路由配置,通常我会在这里的路由中添加一个命名空间,以防止路由配置冲突 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home&quo

asp.net MVC动态路由

项目中遇到需要动态生成控制器和视图的. 于是就折腾半天,动态生成控制器文件和视图文件,但是动态生成控制器不编译是没法访问的. 找人研究后,得到要领: 1.放在App_Code文件夹内 2.不要命名空间 功能虽然实现了,可是觉得这个发放实在有些挫,心里老挂念这个事情.想着既然使用MVC,能不能实现动态路由访问呢? 果然找到两篇相关的文章,解决了问题: 1.http://www.cnblogs.com/gyche/p/5216361.html 2.http://stackoverflow.com/q

ASP.NET MVC自定义路由 - 实现IRouteConstraint限制控制器名(转载)

自定义约束前 namespace MvcApplication2 { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //默认 routes.MapRoute( name: "Default", url: "{controller}/

对ASP.NET MVC 的路由一点理解

这个东西,真搞不懂.看了网上的教程和文章,也不懂(也不清楚写那些文章的人自己是否真的懂).只好靠自己一顿乱摸索. 好比说,下面这个路由: //路由1 config.Routes.MapHttpRoute( name: "SysApi", routeTemplate: "api/SysManager/{action}/{id}", defaults: new { controller = "SysManager", id = RouteParame