How would I configure the global.config to allow for root path to actionMethod in MVC2?

廉价感情. 提交于 2019-12-13 00:22:46

问题


specifically, the default directory naming structure is [Controller]/[ActionMethod] resulting in a rendered url like www.mysite.com/home/actionMethodName.

What if I want to simply imply the Controller (in this example, 'home') so that I can get a url that looks like this: www.mysite.com/actionMethodName.

I haven't seen many requests for this kind of configuration. I can see how it breaks convention, but I would imagine that there are lots of people who need root pathing.


回答1:


Because you are planning to remove the {controller} element of the url, you may need to get a bit more specific with your other urls, e.g.:

routes.MapRoute("MyOtherControllerRoute", "Account/{action}", new { controller = "Account", action = "Index" });
routes.MapRoute("MyDefaultRoute", "{action}", new { controller = "Home", action = "Index" });

When the route table is interrogated, if the url such as www.mysite.com/Account is used, it will match the first route, because we have been specific about the pattern used to match the url. If we then do something like www.mysite.com/DoSomething it will use the default route we've selected last, trying to invoke the DoSomething action on the HomeController type.

Something which I've noticed is that a lot of MVC developers seems to assume that the url is strictly {something}/{something}/{something}, whereas it can essentially be anything you like, e.g, I can have a route that does: www.mysite.com/my-weird-and-wonderful-url which I could map specifically:

routes.MapRoute("Somewhere", "my-weird-and-wonderful-url", new { controller = "Whatever", action = "Whenever" });

Hope that helps.




回答2:


Easy as apple pie - you just specify a route of your own! =)

An example:

routes.MapRoute(
    "RootPathing",
    "{action}",
    new { controller = "Default", action = "Index" });

This will register a route that catches all paths, and try to map them to the DefaultController with an action name corresponding to the path. However, note that if you place this route above the included default route, you will not be able to reach any other controller than the DefaultController - hence, place this route below the default route in the chain. It will then be matched by all paths that don't match a controller name. When debugging routes, Phil Haack's Routing Debugger is really worth taking a look at.



来源:https://stackoverflow.com/questions/3353892/how-would-i-configure-the-global-config-to-allow-for-root-path-to-actionmethod-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!