使用默认控制器的ASP.NET MVC路由

Tra*_*v L 14 asp.net-mvc routing

对于一个场景,我有一个ASP.NET MVC应用程序,其URL如下所示:

http://example.com/Customer/List
http://example.com/Customer/List/Page/2
http://example.com/Customer/List
http://example.com/Customer/View/8372
http://example.com/Customer/Search/foo/Page/5
Run Code Online (Sandbox Code Playgroud)

这些URL通过以下路由实现 Global.asax.cs

routes.MapRoute(
    "CustomerSearch"
    , "Customer/Search/{query}/Page/{page}"
    , new { controller = "Customer", action = "Search" }
);

routes.MapRoute(
    "CustomerGeneric"
    , "Customer/{action}/{id}/Page/{page}"
    , new { controller = "Customer" }
);

//-- Default Route
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Customer", action = "Index", id = "" }
);
Run Code Online (Sandbox Code Playgroud)

这些都进展顺利,直到新的要求到达并希望从URL中删除关键字"客户",以使URL看起来像:

http://example.com/List
http://example.com/List/Page/2
http://example.com/List
http://example.com/View/8372
http://example.com/Search/foo/Page/5
Run Code Online (Sandbox Code Playgroud)

编辑:更正了示例链接,感谢@haacked.

我尝试添加new MapRoutes{action}仅采用并将默认控制器设置为Customer.例如/

routes.MapRoute(
    "CustomerFoo"
    , "{action}"
    , new { controller = "Customer", action = "Index" }
);
Run Code Online (Sandbox Code Playgroud)

这似乎有效,但是现在Html.ActionLink()生成的所有链接都很奇怪,不再是URL友好的.

那么,这是可以实现的吗?我正朝着正确的方向前进吗?

egl*_*ius 16

不要混合使用以下规则:特别是当"{action}/{id}"后者中的"{controller}/{action}/{id}"id具有默认值时,即...是可选的.

在这种情况下,您没有任何东西允许路由知道哪一个是正确的使用.

解决方法,如果你需要的话,就是在一组值(即List,View)中添加一个约束(见这个)给前面的动作.当然,对于这些类型的规则,您不能拥有具有相同操作名称的控制器.

另请记住,如果您在"{action}/{id}"规则中指定了默认操作和ID ,则会在您点击网站路线时使用该操作.


Haa*_*ked 10

为什么新列表中的第一个URL仍然具有"客户".我认为这是一个错字,你的意思是:

以下路线适合我:

routes.MapRoute(
    "CustomerSearch"
    , "Search/{query}/Page/{page}"
    , new { controller = "Customer", action = "Search" }
);

routes.MapRoute(
    "CustomerGeneric"
    , "{action}/{id}/Page/{page}"
    , new { controller = "Customer" }
);

//-- Default Route
routes.MapRoute(
    "Default",
    "{action}/{id}",
    new { controller = "Customer", action = "Index", id = "" }
);
Run Code Online (Sandbox Code Playgroud)

你是如何生成链接的?由于Controller不再位于路由的URL中(也就是说,路由URL中没有"{controller}"),但它是默认值,因此您需要确保在生成路由时指定控制器.

因此而不是

Html.ActionLink("LinkText", "ActionName")
Run Code Online (Sandbox Code Playgroud)

Html.ActionLink("LinkText", "ActionName", "Customer")
Run Code Online (Sandbox Code Playgroud)

为什么?假设您有以下路线.

routes.MapRoute(
    "Default",
    "foo/{action}",
    new { controller = "Cool" }
);

routes.MapRoute(
    "Default",
    "bar/{action}",
    new { controller = "Neat" }
);
Run Code Online (Sandbox Code Playgroud)

你打电话给这条路是什么意思?

<%= Html.ActionLink("LinkText", "ActionName") %>
Run Code Online (Sandbox Code Playgroud)

您可以通过指定控制器来区分,我们将选择具有与指定控制器匹配的默认值的控制器.