How can I create a MapRoute entry in ASP.NET MVC that only matches if there is no further path?
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).
There is an IgnoreRoute
method which you can use to ignore route, maybe the following would do what you need:
routes.IgnoreRoute("Users/{*pathInfo}");
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]+
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
- /Users/etc/etc
- /Users/etc
- /Users (as a catch all)
hope this helps?
more information about routing can be found here http://www.asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs
Here is exact solution:
Just replace places of id
and action
in url
parameter, you got it:
"Users/{action}/{id}"
=> "Users/{id}/{action}"
routes.MapRoute(
"Users",
"Users/{id}/{action}",
new { controller = "Users", action = "Index", id = UrlParameter.Optional});
Even with this:
id = UrlParameter.Optional
you can have yourapp.com/Users
or yourapp.com/Users/whatever
referring answer How do I change the order of routes.MapRoute in MVC3?
精彩评论