Asp.Net MVC 路由匹配

                                                                                                           Asp.Net MVC 路由匹配

一、关于{controller}/{action}

(1)、必不可少:在一个是实际的MVC系统中,{controller}/{action}是必不可少的,如果没有就会因为找不到路径而出错

(2)、约定规则:这个占位符是MVC里面约定的,并会自动解析为控制器和对应的动作方法

(3)、位置灵活:这两个约定的占位符可以在任意位置

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 = "Admin", action = "Index", id = UrlParameter.Optional }
);
//含有常量的路由
routes.MapRoute(
name: "test0",
url: "{first}/{second}/{third}/{forth}/aspx",
defaults: new { controller = "Work", action = "Index", id = UrlParameter.Optional }
);
//只有一个控制器的路由
routes.MapRoute(
name: "test1",
url: "{year}/{month}/{day}/{controller}",
defaults: new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
);
//只有一个动作方法的路由
routes.MapRoute(
name: "test2",
url: "{action}/{article}/{author}/{year}/{month}/{day}",
defaults: new { controller = "Work", action = "Index", id = UrlParameter.Optional }
);

}
}

注:如果某个路由出现错误可能是被在它之前的路由截取了,可以改变位置或者改变路由解决问题

二、其他占位符

(1)、仅仅是占位:比如{aa}/{bb}/{cc},{aa}不能被解析为控制器{bb}也不能被解析为动作方法

(2)、默认要求:如果一个路由中没有规定的{controller}/{action},或者只是规定了其中之一,没有规定的部分则使用默认值。例如

url: "{year}/{month}/{day}/{controller}",

defaults: new { controller = "Work", action = "Index", id = UrlParameter.Optional }

这个路由匹配到的Url默认是由Work控制器中的Index方法

三、匹配顺序

(1)、优先使用:多个路由匹配一个Url,则优先匹配的会使用

(2)、尽量避免:定义多个路由时,尽量避免多匹配

猜你喜欢

转载自www.cnblogs.com/zjifafengfang/p/12020675.html