MVC4的mapRoute URL - {controller} / {action} vs Controller / {action}。有什么不同?

时间:2013-01-25 19:34:55

标签: c# asp.net-mvc-4 routing

我最近因为这两条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}设置所有路由的默认值?

1 个答案:

答案 0 :(得分:5)

您认为{controller}子字符串充当控制器名称的占位符是正确的。考虑到这一点,然后,以下路由将匹配任何控制器,但默认为没有指定控制器的User控制器:

routes.MapRoute(
    "post-User",
    "{controller}",
    new { controller = "User", action = "create" },
    new { httpMethod = new HttpMethodConstraint("POST") }
);

但是,以下内容将匹配路由User并且 - 因为无法指定控制器 - 始终路由到User控制器:

routes.MapRoute(
    "post-User",
    "User",
    new { controller = "User", action = "create" },
    new { httpMethod = new HttpMethodConstraint("POST") }
);

在这种情况下,差异是没有意义的,因为您所做的只是强制路线User映射到控制器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控制器匹配,并指定了可选操作,默认为MyDefaultAction。对任何其他控制器的请求将不会匹配第一条路由 - 因为路由不以常量字符串User开头 - 并且将默认返回第二条路由(富)。同样,行动是可选的;但是,现在,与User控制器的请求不同,其他控制器的默认操作将是Index操作。

所以现在......

.../User默认为MyDefaultAction操作。

.../SomeOtherController默认为Index操作。

相关问题