ASP.NET MVC路由与默认的控制器 [英] ASP.NET MVC Routing with Default Controller
问题描述
有关的场景,我有网址看起来像下面这样的ASP.NET MVC应用程序:
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
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 = "" }
);
这些都进展顺利,直到一个新的需求到来,想放弃关键字客户断网址,让网址如下:
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
取 {行动}
只,并已默认控制器设置为客户。例如:/
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?
推荐答案
不要混用如下规则:一个{行动} / {ID}
这是{控制器} / {行动} / {ID}
...特别是当ID在以后有默认值即是可选的。
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.
有一个解决办法,如果这是你所需要的,将是增加一个约束(见<一href=\"http://stephenwalther.com/blog/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx\">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.
还要记住,如果你指定一个默认的行为和放大器; 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屋!