MVC路由

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

  

这是我们页面初始化创建的路由

当一个MVC应用程序首次运行时,会调用Application_Start()方法。这个方法随后调用了RegisterRoutes()方法。RegisterRoutes()方法创建了路由表。

默认的路由表包含了一个路由(名叫Default)。Default路由将URL的第一部分映射到控制器名,URL的第二部分映射到控制器动作,第三个部分映射到一个叫做id的参数。

假设你在浏览器的地址栏输入了下面的URL:

/Home/Index/3

  

默认的路由将这个URL映射为下面的参数:

Controller = Home

Action = Index

id = 3

  

当你请求URL /Home/Index/3时,将会执行下面的代码:

HomeController.Index(3)

  

Default路由包含了所有三个参数的默认值。如果你不提供控制器,那么控制器参数默认值为Home。如果你不提供动作,动作参数默认为值Index。最后,如果你不提供id,id参数默认为空字符串。

加入我们输入的地址

/Home

由于Default路由参数的默认值,输入这个URL将会调用代码清单2中的HomeController类的Index()方法。因为没有adction的时候会默认到Index()

创建自定义路由

假如我们现在要做一个博客 地址如下/Archive/12-25-2009  这样的地址想要显示的是12月25日期下所有的内容列表

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                "Blog",                                           // Route name
                "Archive/{entryDate}",                            // URL with parameters
                new { controller = "Archive", action = "Entry" }  // Parameter defaults
            );


            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

  

必须要将Bolg的路由放在Default前面 因为Default也满足Bolg的路由 所以 在特殊路由的情况下应该放在Default前面 不然会被拦截

在Bolg在 Archive没有被{}包起来,说明是个常量,这里意思就是在所有的Archive的controller里面去匹配 如果输入的controller能匹配的到就去匹配,匹配不到就会到默认

Entry的controller中

约束

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"}
);

  

下面这段路由 实际上我们想带入一个方法 这个方法只能接受数字类型

但是 下面的都会执行

/Product/23
/Product/7

  

不幸的是,路由也会匹配下面的URL:

/Product/blah
/Product/apple

  

这时候就会报错,所以我们必须要对参数经行约束

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"d+" }
 );

  

正则表达式d+匹配一个或多个整数。这个限制使得Product路由匹配了下面的URL:

/Product/3
/Product/8999

  

但是不匹配下面的URL:

/Product/apple
/Product

  

原文地址:https://www.cnblogs.com/linsong521/p/4754296.html