MVC5路由系统机制详细讲解

请求一个ASP.NET  mvc的网站和之前的web form是有区别的,ASP.NET MVC框架内部给咱们提供了路由机制,当IIS接受到一个请求时,会先看是否请求了一个静态资源(.html,css,js,图片等),这一步是web form和mvc都是同样的,若是不是说明则说明是请求的一个动态页面,就会走asp.net的管道,mvc的程序请求都会走路由系统,会映射到一个Controller对应的Action方法,而web form请求动态页面是会查找本地实际存在一个aspx文件。下面经过一个ASP.NET MVC5项目来详细介绍一下APS.NET MVC5路由系统的机制。

1、认识Global.asax.cs

当咱们建立一个APS.NET MVC5的项目的时候会在项目的根目录中生成一个Global.asax文件。
  1. public class MvcApplication : System.Web.HttpApplication
  2. {
  3. protected void Application_Start()
  4. {
  5. //注册 ASP.NET MVC 应用程序中的全部区域
  6. AreaRegistration.RegisterAllAreas();
  7. //注册 全局的Filters
  8. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  9. //注册 路由规则
  10. RouteConfig.RegisterRoutes(RouteTable.Routes);
  11. //注册 打包绑定(js,css等)
  12. BundleConfig.RegisterBundles(BundleTable.Bundles);
  13. }
  14. }

 

这个Application_Start方法会在网站启动的自动调用,其中咱们看到:RouteConfig.RegisterRoutes(RouteTable.Routes);这个就是向ASP.NET MVC 框架注册咱们自定义的路由规则,让以后的URL可以对应到具体的Action。接下来咱们再来看看RegisterRoutes方法作了些什么?
  1. public class RouteConfig
  2. {
  3. public static void RegisterRoutes(RouteCollection routes)
  4. {
  5. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  6. routes.MapRoute(
  7. name: "Default",
  8. url: "{controller}/{action}/{id}",
  9. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  10. );
  11. }
  12. }

 

上面代码是vs自动为大家生成,只定义了一个默认规则。
一、规则名:Default
二、URL分段:{controller}/{action}/{id},分别有三段,第一段对应controller参数,第段为action参数,第三段为id参数
三、URL段的默认值:controller为Home,action为Index,id = UrlParameter.Optional表示该参数为可选的。
之因此咱们访问http://www.xx.com/ 这样的URL网址能正确返回,是由于咱们设置了URL段的默认值,至关于访问:
http://www.xx.com/Home/Index
 
RegisterRoutes调用的是RouteCollection的MapRoute方法,RouteCollection是一个集合,继承于Collection<RouteBase>
 

3、ASP.NET MVC默认的命名约定

一、Controller命名约定

Controller类必须以Controller结尾,好比:HomeController,ProductController。咱们在页面上用HTML heper来引用一个Controller的时只须要前面Home,Product就能够,ASP.NET MVC框架自带的DefaultControllerFactory自动为咱们在结尾加上Controller,并开始根据这个名字开始找对应的类。咱们建立一个ASP.NET MVC项目新加的Controller,文件会自动放在根目录的Controllers文件夹里面,咱们刚开始能够看到有一个HomeController.cs。固然你也能够实现接口IControllerFactory,定义本身的ControllerFactory来改变查找Controller文件的行为。我会再之后的文章中介绍。

二、View命名约定

ASP.NET MVC的视图View默认状况是放在根目录的Views文件下的,规则是这样的:/Views/ControllerName/ActionName.cshtml。好比:HomeController的Action名字为Index的视图对应文件为:/Views/Home/Index.cshtml
所以是经过Controller和Action的名字来肯定视图文件的位置的。采用这个命名约定的好处是在Action返回视图的时候会MVC框架会按照这个约定找到默认的视图文件。好比在ProductController的Action方法List最后是这样的代码:
return View();
会自动去路径,/Views/Product/找文件List.cshtml(或者List.aspx若是使用的老的视图引擎)。
固然也能够指定视图的名字:
return View("~/Views/Product/List.cshtml")
或者
return View("MyOtherView")
 
MVC框架在查找具体的默认视图文件时,若是在/Views/ControllerName/下面没有找到,会再在/Views/Shared下面找,若是都没找到就会找错:找不到视图。
 

4、ASP.NET MVC的URL规则说明

最开始咱们在网站的Application_Start事件中注册一些路由规则routes.MapRoute,当有请求过来的时候,mvc框架会用这些路由规则去匹配,一旦找到了符合要求就去处理这个URL。例若有下面这个URL:
http://mysite.com/Admin/Index
URL能够分为几段,除去主机头和url查询参数,MVC框架是经过/来把URL分隔成几段的。上面的URl分为两段。以下图:
第一段的值为Admin,第二段的值为Index,咱们是很容易看出Admin对应就是Controller,Index就是Action。可是咱们要告诉MVC框架这样的规则,所以为下面的Application_Start有下面的代码:
  1. routes.MapRoute(
  2. name: "Default",
  3. url: "{controller}/{action}/{id}",
  4. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  5. );
上面表示URL规则是:
{controller}/{action} 
这个路由规则有两个段,第一个是controller,第二个是action。声明url段每一个部分要且{}括起来,至关于占位符,是变量。
当一个URL请求到来的时候MVC路由系统就负责把它匹配到一个具体的路由规则,并把URL每段的值提取出来。这里说“一个具体的路由规则”,是由于可能会注册多个路由规则,MVC路由系统会根据注册顺序一个一个的查找匹配,直到到为止。
默认状况,URL路由规则只匹配与之有相同URL段数量的URL。以下表:
URL
URL段
http://mysite.com/Admin/Index
controller = Admin
action = Index 
http://mysite.com/Index/Admin
controller = Index
action = Admin 
http://mysite.com/Apples/Oranges
controller = Apples
action = Oranges
http://mysite.com/Admin
无匹配-段的数量不够
http://mysite.com/Admin/Index/Soccer
无匹配-段的数量超了
 

5、mvc建立一个简单的Route规则

咱们在前面注册路由规则都是经过下面的方式:
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}");
  3. }

 

用到了RouteCollection的MapRoute方法。其实咱们还能够调用 Add方法,传一个Route的实例给它同样的达到相同的效果。
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. Route myRoute = new Route("{controller}/{action}", new MvcRouteHandler());
  3. routes.Add("MyRoute", myRoute);
  4. }

6、mvc路由的默认值的设定

以前有说:URL路由规则只匹配与之有相同URL段数量的URL,这种是严格,可是咱们又想有些段不用输入,让用户进入指定的页面。像,http://www.xx.com/Home/就是进入进入Home的Index。只须要设定mvc路由的默认值就能够了。
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}", new { action = "Index" });
  3. }

 

要设置Controller和Action的默认值。
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}",
  3. new { controller = "Home", action = "Index" });
  4. }

 

下面是一个具体的Url对应的Route映射。
Url段的数量
实例
Route映射
0
mydomain.com 
controller = Home
action = Index 
1
mydomain.com/Customer
controller = Customer
action = Index 
2
mydomain.com/Customer/List
controller = Customer
action = List 
3
mydomain.com/Customer/List/All
无匹配—Url段过多 
 

7、mvc使用静态URL段

前面定义路由规则都是占位符的形式,{controller}/{action},咱们也可使用在使用静态字符串。如:
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}",
  3. new { controller = "Home", action = "Index" });
  4. routes.MapRoute("", "Public/{controller}/{action}",
  5. new { controller = "Home", action = "Index" });
  6. }

 

上面匹配:http://mydomain.com/Public/Home/Index
路由:"Public/{controller}/{action}"只匹配有三段的url,第一段必须为Public,第二和第三能够是任何值,分别用于controller和action。
除此这外,路由规则中能够既包含静态和变量的混合URL段,如:
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("", "X{controller}/{action}");
  3. routes.MapRoute("MyRoute", "{controller}/{action}",
  4. new { controller = "Home", action = "Index" });
  5. routes.MapRoute("", "Public/{controller}/{action}",
  6. new { controller = "Home", action = "Index" });
  7. }

8、mvc的路由中自定义参数变量

mvc框架除了能够定义自带的controller和action的参数以外,还能够定义自带的变量。以下:
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
  3. new { controller = "Home", action = "Index", id = "1" });
  4. }

 

上面定义了一个id,默认值咱们设为1。
这个路由能够匹配0-3个url段的url,第三个url段将被用于id。若是没有对应的url段,将应用设置的的默认值。
自定义参数变量使用:
方法1、
  1. public ViewResult CustomVariable() {
  2. ViewBag.CustomVariable = RouteData.Values["id"];
  3. return View();
  4. }

 

MVC框架从URL获取到变量的值均可以经过RouteData.Values["xx"],这个集合访问。
方法2、
public ViewResult CustomVariable(int id) {
 
ViewBag.CustomVariable = id;
    return View();
}
MVC框架使用内置的Model绑定系统将从URL获取到变量的值转换成Action参数相应类型的值。这种转换除了能够转换成基本int,string等等以外还能够处理复杂类型,自定义的Model,List集合等。相关参考: MVC中默认Model Binder绑定Action参数为List、Dictionary等集合的实例
 

9、mvc定义可选URL段、可选参数

asp.net mvc定义 参数是也能够设置为可选的,这样用户能够不用输入这部分的参数。

一、注册路由时定义可选URL段

public static void RegisterRoutes(RouteCollection routes) {
 
    routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
 

二、经过Action参数来定义可选参数

public ViewResult CustomVariable(string id = "DefaultId") {
 
ViewBag.CustomVariable = id;
    return View();
经过Action参数来定义可选参数是没有加默认值的,而经过注册路由时定义可选URL段是加了默认值的,是利用c#参数的默认参数特性。这样若是用户没有输入这部分url段,就会默认值就会被使用。
 

10、mvc使用*来定义变长数量的URL段

除了在路由规则中声明固定的数量的URL段,咱们也能够定义变长数量的URL段,以下面代码:
public static void RegisterRoutes(RouteCollection routes) {
 
    routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
经过变量前面加一个星号(*)开头就能匹配任意变长数量的URL。
匹配URL以下:
Url段的数量
实例
Route映射
0
mydomain.com 
controller = Home
action = Index 
1
mydomain.com/Customer
controller = Customer
action = Index 
2
mydomain.com/Customer/List
controller = Customer
action = List 
3
mydomain.com/Customer/List/All
controller = Customer
action = List
id = All 
4
mydomain.com/Customer/List/All/Delete
controller = Customer
action = List
id = All
catchall = Delete  
5
mydomain.com/Customer/List/All/Delete/Perm
controller = Customer
action = List
id = All
catchall = Delete /Perm

11、mvc使用命名空间来为路由的Controller类定优先级

当一个用户输入一个URL请求ASP.NET MVC的网站时,ASP.NET MVC会根据URL的获取请求是找到是哪个Controller类,若是一个项目有多相同的类名的Controller,就会有问题。好比:当请求的变量controller的值为Home时,MVC框架就会去找一个Controller名字为HomeController的类,这个类(HomeController)默认是不受限制的,若是多个命名空间都有名字为HomeContoller的类, ASP.NET MVC就不知道怎么办了。当这种状况发生是,就会报错:
“/”应用程序中的服务器错误。
找到多个与名为“Home”的控制器匹配的类型。若是为此请求(“{controller}/{action}/{id}”)提供服务的路由没有指定命名空间以搜索与此请求相匹配的控制器,则会发生这种状况。若是是这样,请经过调用带有 'namespaces' 参数的 "MapRoute" 方法的重载来注册此路由。
 
“Home”请求找到下列匹配的控制器:
WebApplication1.Controllers.HomeController
WebApplication1.Controllers1.HomeController 
 
[InvalidOperationException: 找到多个与名为“Home”的控制器匹配的类型。若是为此请求(“{controller}/{action}/{id}”)提供服务的路由没有指定命名空间以搜索与此请求相匹配的控制器,则会发生这种状况。若是是这样,请经过调用带有 'namespaces' 参数的 "MapRoute" 方法的重载来注册此路由。
“Home”请求找到下列匹配的控制器:
解决办法:
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("Default",
  3. "{controller}/{action}/{id}",
  4. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  5. new string[] { "WebApplication1.Controllers" }
  6. );
  7. }

 

上面MapRoute的最后一个参数,new string[] { "WebApplication1.Controllers" }就是指定先去命名空间为WebApplication1.Controllers查找在controller,若是找到就中止往下找,没找到仍是会去其它命名空间中去找的。所以当你指定的这个命名空间若是没存在要找的controller类,而在其它命名空间是有的,是会正常执行的,因此这里指定命名空间并非限定了命名空间,而只是设了一个优先级而已。
 

12、mvc定义路由规则的约束

在前面咱们介绍了为mvc路由的规则设置路由默认值和可选参数,如今咱们再深刻一点,咱们要约束一下路由规则。

一、用正则表达式限制asp.net mvc路由规则

  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  3. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  4. new { controller = "^H.*"},
  5. new[] { "URLsAndRoutes.Controllers"});
  6. }

 

上面用到正则表达式来限制asp.net mvc路由规则,表示只匹配contorller名字以H开头的URL。

二、把asp.net mvc路由规则限制到到具体的值

  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  3. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  4. new { controller = "^H.*", action = "^Index$|^About$"},
  5. new[] { "URLsAndRoutes.Controllers"});
  6. }

 

上例在controller和action上都定义了约束,约束是同时起做用是,也就是要同时知足。上面表示只匹配contorller名字以H开头的URL,且action变量的值为Index或者为About的URL。
 

三、把asp.net mvc路由规则限制到到提交请求方式(POST、GET)

  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  3. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  4. new { controller = "^H.*", action = "Index|About",
  5. httpMethod = new HttpMethodConstraint("GET") },
  6. new[] { "URLsAndRoutes.Controllers" });
  7. }

上面表示只匹配为GET方式的请求。javascript

四、使用接口IRouteConstraint自定义一个asp.net mvc路由约束

下面我自定义一个约束对特定浏览器进行处理。
UserAgentConstraint.cs:
  1. using System.Web;
  2. using System.Web.Routing;
  3. namespace URLsAndRoutes.Infrastructure {
  4. public class UserAgentConstraint : IRouteConstraint {
  5. private string requiredUserAgent;
  6. public UserAgentConstraint(string agentParam) {
  7. requiredUserAgent = agentParam;
  8. }
  9. public bool Match(HttpContextBase httpContext, Route route, string parameterName,
  10. RouteValueDictionary values, RouteDirection routeDirection) {
  11. return httpContext.Request.UserAgent != null &&
  12. httpContext.Request.UserAgent.Contains(requiredUserAgent);
  13. }
  14. }
  15. }

 

asp.net mvc自定义路由约束的使用:
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  3. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  4. new {
  5. controller = "^H.*", action = "Index|About",
  6. httpMethod = new HttpMethodConstraint("GET", "POST"),
  7. customConstraint = new UserAgentConstraint("IE")
  8. },
  9. new[] { "URLsAndRoutes.Controllers" });
  10. }
上面表示这个路由规则只匹配用户使用IE浏览器的请求。利用这点咱们就能够实现不一样浏览器使用不一样的Controller,进行不一样的处理。虽然这样作的意义不大,可是不排除有时会有这种变态的需求。
 

十3、mvc将URL路由到磁盘文件

mvc的网站并非因此的url请求都是对应controller,action,咱们仍然要一种方式来提供一些静态内容,好比:html文件,css,图片,javascript文件些,其实默认状况下mvc框架在在收到url请求时会先判断这个url是不是对应一个磁盘中真实存在的文件,若是是直接返回,这时路由是没有使用到的,若是不是真实存在的文件时才会走路由系统,再去匹配注册的路由规则。
这种默认的处理url机制顺序咱们也能够改变它,让在检查物理文件以前就应用路由,以下:
  1. public static void RegisterRoutes(RouteCollection routes) {
  2. routes.RouteExistingFiles = true;
  3. routes.MapRoute("DiskFile", "Content/StaticContent.html",
  4. new {
  5. controller = "Account", action = "LogOn",
  6. },
  7. new {
  8. customConstraint = new UserAgentConstraint("IE")
  9. });
  10. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  11. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  12. new {
  13. controller = "^H.*", action = "Index|About",
  14. httpMethod = new HttpMethodConstraint("GET", "POST"),
  15. customConstraint = new UserAgentConstraint("IE")
  16. },
  17. new[] { "URLsAndRoutes.Controllers" });
  18. }

 

 
咱们把RouteExistingFiles属性设置为true,表示存在的文件也走路由,上面咱们把Content/StaticContent.html这个文件映射到controller 为Account,action 为LogOn中了,而并非指磁盘中存在的文件。基于asp.net mvc的这个特性咱们就能够实现mvc以.html结尾的伪静态,具体实现方式请看我之前写的文章: 教你如何在asp.net mvc中实现高性能以html结尾的伪静态
 

十4、mvc跳过、绕开路由系统设定

上面咱们用使用routes.RouteExistingFiles = true,让全部的请求都走路由系统过一下,不免有一些性能影响,由于一些图片,一些真正的html,文件是没有必要的。咱们能够对些文件作一些起特殊设定让它们跳过、绕开路由系统。下面就是让Content目录下的全部文件都绕开mvc的路由系统:
      1. public static void RegisterRoutes(RouteCollection routes) {
      2. routes.RouteExistingFiles = true;
      3. routes.MapRoute("DiskFile", "Content1/StaticContent.html",
      4. new {
      5. controller = "Account", action = "LogOn",
      6. },
      7. new {
      8. customConstraint = new UserAgentConstraint("IE")
      9. });
      10. routes.IgnoreRoute("Content/*{filename}");
      11. routes.MapRoute("", "{controller}/{action}");
      12. }
相关文章
相关标签/搜索