带有默认控制器的 ASP.NET MVC 路由 [英] ASP.NET MVC Routing with Default Controller
问题描述
对于一个场景,我有一个 ASP.NET MVC 应用程序,其 URL 如下所示:
For a scenario, I have a ASP.NET MVC application with URLs that look like the following:
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
这些 URL 是通过 Global.asax.cs
These URLs are achieved with following routes in 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 = "" }
);
这些都进行得很顺利,直到一个新的需求出现并且想要从 URL 中删除关键字客户",使 URL 看起来像:
These all have gone well until a new requirement arrived and wants to drop keyword 'Customer' off the URL, to make the URLs look like:
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
更正示例链接,感谢@haacked.
corrected example links, thanks to @haacked.
我尝试添加新的 MapRoutes
以仅采用 {action}
并将默认控制器设置为 Customer.例如/
I tried to add new MapRoutes
to take {action}
only and have default controller set to Customer. eg/
routes.MapRoute(
"CustomerFoo"
, "{action}"
, new { controller = "Customer", action = "Index" }
);
这似乎有效,但是现在所有由 Html.ActionLink() 生成的链接都很奇怪并且不再对 URL 友好.
This seems to work, however now all links generated by Html.ActionLink() are weird and no longer URL friendly.
那么,这可以实现吗?我的方向是否正确?
So, is this achievable? Am I approaching in the right direction?
推荐答案
不要将诸如 "{action}/{id}"
之类的规则与 "{controller}/{action}/{id}"
... 特别是当后面的 id 有一个默认值 ie 是可选的.
don't mix a rule like: "{action}/{id}"
with one that's "{controller}/{action}/{id}"
... specially when id in the later has a default value i.e. is optional.
在这种情况下,您没有任何东西可以让路由知道使用哪个是正确的.
In that case you have nothing that allows routing to know which one is the right one to use.
如果这是您需要的解决方法,那就是添加约束(请参阅 this) 到前面的动作到一组值即列表、视图.当然,对于这些类型的规则,您不能拥有与操作名称相同的控制器.
A workaround, if that's what you need, would be to add a constrain (see this) to the action in the earlier to a set of values i.e. List, View. Of course that with these types of rules, you can't have a controller with the same name of an action.
还请记住,如果您指定默认操作 &"{action}/{id}"
规则中的 id,当你点击你网站的路由时会用到.
Also remember that if you specify a default action & id in the "{action}/{id}"
rule, that will be used when you hit the route of your site.
这篇关于带有默认控制器的 ASP.NET MVC 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!