我最近对这两个 MVC4 路由显然功能不同这一事实感到恼火。我想知道是否有人可以突出显示正在发生的事情,以便我更好地理解。
routes.MapRoute(
"post-User",
"User",
new { controller = "User", action = "create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
"post-User",
"{controller}",
new { controller = "User", action = "create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
我认为 {controller} 位是一个占位符,在下一行中说 controller = "User"会使这两个语句等价。显然使用 {controller} 为所有路由设置默认值?
最佳答案
您认为 {controller}
子字符串充当 Controller 名称的占位符是正确的。考虑到这一点,下面的路由将匹配任何 Controller ,但默认匹配未指定 Controller 的User
Controller :
routes.MapRoute(
"post-User",
"{controller}",
new { controller = "User", action = "create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
然而,以下内容将匹配路由 User
并且 - 因为无法指定 Controller - 将始终路由到 User
Controller :
routes.MapRoute(
"post-User",
"User",
new { controller = "User", action = "create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
在这种情况下,差异是没有意义的,因为您所做的只是强制路由 User
映射到 Controller User
,这正是您的无论如何第一条路线。
但是,请考虑以下几点:
routes.MapRoute(
"post-User",
"User/{action}",
new { controller = "User", action = "MyDefaultAction" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
"foo",
"{controller}/{action}",
new { controller = "User", action = "Index" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
现在,您的顶级路由将匹配对 User
Controller 的请求,并指定一个可选操作并将默认为 MyDefaultAction
。对任何其他 Controller 的请求将不会匹配第一条路由——因为该路由不是以常量字符串User
开头——并且将默认返回到第二条路线(foo)。同样,该操作是可选的;但是,现在,与对 User
Controller 的请求不同,您对其他 Controller 的默认操作将是 Index
操作。
那么现在...
.../User
默认为 MyDefaultAction
操作。
.../SomeOtherController
默认为 Index
操作。
关于c# - MVC 4's mapRoute URL -- {controller}/{action} vs Controller/{action}. What' 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14529098/