asp.net-mvc ASP.NET MVC 默认路由?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/973205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC Default route?
提问by George Stocker
I created a new ASP.NET MVC project and implemented a site authorization filter.
我创建了一个新的 ASP.NET MVC 项目并实现了一个站点授权过滤器。
When I map the routes to the {controller}/{action}pair, I pass a role = "SomeRole" default to the route.
当我将路由映射到{controller}/{action}对时,我将默认的角色 = "SomeRole" 传递给路由。
It works perfectly if I go through the full url (http://localhost/somecontroller/someaction) and I specified the full route
如果我通过完整的 url ( http://localhost/somecontroller/someaction) 并指定完整的路线,它会完美地工作
MapRoute("SomeAction", "somecontroller/someaction",
new { controller = "SomeController", action = "SomeAction", role = "SomeRole");
The problem is that when somebody visits http://thesiteaddress.comthere has to be a default route that invokes /home/indexinstead of /and if I specify
问题是,当有人访问时http://thesiteaddress.com,必须有一个默认路由来调用/home/index而不是/如果我指定
MapRoute("Default", new { controller="somecontroller",action="action" });
then I lose the role="SomeRole"from the previous MapRoute.
然后我失去role="SomeRole"了以前的MapRoute.
How can I solve this?
我该如何解决这个问题?
回答by George Stocker
Make sure the Defaultroute is at the BOTTOMof your listed route table. Order matters when it comes to ASP.NET MVC Routing tables.
确保Default路线位于您列出的路线表的底部。当涉及到 ASP.NET MVC 路由表时,顺序很重要。
The correct ordering is your 'most specific' route to your least specific route.
正确的顺序是从“最具体”的路线到最不具体的路线。
回答by Jirapong
Actually, George is right. MVC Routing respect ordering route. Your last route must be generic as possible, and your previous route must be specific as possible.
事实上,乔治是对的。MVC 路由尊重排序路由。您的最后一条路线必须尽可能通用,而您之前的路线必须尽可能具体。
In your case, both are generic. You should
在您的情况下,两者都是通用的。你应该
MapRoute("SomeAction", "Post/{action}", new {controller = "Post", role = "User");
and then
进而
MapRoute("Default", new {controller="Home", action="Index", role = "Anonymous"});
so, you give specificity to both routes.
因此,您对两条路线都给予了特殊性。
回答by Ray Vernagus
回答by Chad Moran
When you don't provide the route name or the action is determined through a HTTP request it will look in order from the order they were added. The first time it finds one that matches, it stops. So what's probably happening is it's matching one previous to the one you've added.
当您不提供路由名称或通过 HTTP 请求确定操作时,它将按照添加顺序进行查找。当它第一次找到匹配的时,它就会停止。所以可能发生的事情是它与您添加的前一个匹配。

