如何在 ASP.NET MVC 中创建仅在没有进一步路径时才匹配的 MapRoute 条目?
我想创建一个与“/Users”匹配的 MapRoute 条目,但不会与“/Users/etc”或“/Users/etc/etc”等路径匹配。
我还必须匹配“Users/{id}”(其中 ID 是一个 int)和“Users/Me”(工作正常)。我对 ID 有限制 (@"\d+")。
知道我该怎么做吗?
如果我使用以下内容,它会匹配以上所有内容:
routes.MapRoute(null, "Users", new { controller = "Users", action = "Index" });
我需要使用约束吗?如果是这样,我应该使用什么约束?
我正在使用 ASP.NET MVC 3(如果重要的话)。
I'd like to create a MapRoute entry that will match "/Users", but won't match paths like "/Users/etc" or "/Users/etc/etc".
I have to also match "Users/{id}" (where ID is an int) and "Users/Me" (which are working OK). I have a constraint on ID (@"\d+").
Any idea how I'd go about that?
If I use the following, it matches all of the above:
routes.MapRoute(null, "Users", new { controller = "Users", action = "Index" });
Do I need to use a constraint? If so, what constraint should I use?
I'm using ASP.NET MVC 3 (if it matters).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个
IgnoreRoute
方法,您可以使用它来忽略路由,也许以下内容可以满足您的需要:编辑:
没有真正阅读太多有关 MVC 约束的内容,但它看起来像正则表达式?
您在更新中提到了
\d+
的约束,这只会匹配数字,尝试\S+
它将匹配所有条形空格,问题是,它也可能匹配反斜杠!可能的替代方案是
[a-zA-Z0-9]+
There is an
IgnoreRoute
method which you can use to ignore route, maybe the following would do what you need:edit:
Not really read up that much on constraints for MVC, but it looks like regex?
You mentioned your constraint of
\d+
in your update, this will match only digits, try\S+
which will match everything bar spaces, problem is, it might match backslashes too!A possible alternative would be
[a-zA-Z0-9]+
在 MVC 中指定路由的顺序是重要的部分 - 系统沿着路由向下工作并找到它需要满足的第一个匹配项,
因此一般路由需要在列表中进一步向下(
在本例中是我们的顺序)是
希望这有帮助吗?
有关路由的更多信息可以
可以在这里找到 http://www.asp.net/ mvc/教程/asp-net-mvc-routing-overview-cs
the order in which you specify routes in MVC is the important part - the system works its way down the Routes and finds the first match that it needs to that satisfies
therefore the general routes need to be further down the list
the order in this case our be
hope this helps?
more information about routing can
be found here http://www.asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs
确切的解决方案如下:
只需替换
url
参数中的id
和action
的位置,即可得到:"Users/{action} /{id}"
=>"Users/{id}/{action}"
即使这样:
id = UrlParameter.Optional
,您也可以拥有
yourapp.com/Users
或yourapp.com/Users/whatever
引用答案如何更改MVC3中routes.MapRoute的顺序?
Here is exact solution:
Just replace places of
id
andaction
inurl
parameter, you got it:"Users/{action}/{id}"
=>"Users/{id}/{action}"
Even with this:
id = UrlParameter.Optional
you can have
yourapp.com/Users
oryourapp.com/Users/whatever
referring answer How do I change the order of routes.MapRoute in MVC3?