MVC6个常用路由设置,记录下

大家在学习MVC的过程,老是用到设置路由,但有6个常用路由,是大家经常用到的。

一.默认路由(MVC自带)

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
 
    routes.MapRoute( 
        "Default", // 路由名称 
        "{controller}/{action}/{id}", // 带有参数的 URL 
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 (UrlParameter.Optional-可选的意思)
    ); 
  } 


二.不带参数的路由

 routes.MapRoute
(
"NoParameter", 
"{controller}/{action}/{id}"
);

三.带命名空间的路由

 routes.MapRoute(
              "AdminControllers", // 路由名称
              "{controller}/{id}-{action}", // 带有参数的 URL
              new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值
              new string[] { "Admin.Controllers" }//命名空间
          );

四.带约束的路由规则(约束的意思就是用正则这类约束必须符合条件才可以)

routes.MapRoute(
                "RuleControllers",
                "{controller}/{action}-{Year}-{Month}-{Day}}",
                new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" },
                new { Year = @"^\d{4}", Month = @"\d{2}" } //4位数 2位数
            );

五.带名称空间,带约束,带默认值的路由规则

 routes.MapRoute(
                "Rule1",
                "Admin/{controller}/{action}-{Year}-{Month}-{Day}",
                new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" },
                new { Year = @"^\d{4}", Month = @"\d{2}" },
                new string[] { "Admin.Controllers" }
            );

六.捕获所有的路由

  routes.MapRoute(
                "All", // 路由名称
                "{*Vauler}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

好了,大致就这么多常用路由,出处忘了,做下笔记,送给同样迷茫的同学们!

原文地址:https://www.cnblogs.com/flyfish2012/p/2891354.html