asp mvc routing problem
I have this two routes.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
"Paging", // Route name
"{controller}/{action}/p{currentPage}",
new { controller = "Home", action = "Index" },
new { currentPage开发者_如何学C = "\\d+" });
I have this Controller
public class MyController
{
public ActionResult All(int currentPage = 1)
{
// some code executed here
return View(pList);
}
}
Why this url goes to the first route /My/All/p5
Can someone point me to good tutorial about routes?
Routes need to be registered in the right order, as they are processed in the same order in which they are registered. Your first route is essentially a catch all, so it will also match /My/All/p5
. Register that route first:
routes.MapRoute(
"Paging", // Route name
"{controller}/{action}/p{currentPage}",
new { controller = "Home", action = "Index" },
new { currentPage = "\\d+" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Reading : Steven Sanderson has very good explanation of routing in his book ( Pro MVC 2 ) in chapter 8. (You can find it here)
From the book:
If there’s one golden rule of routing, this is it: put more-specific route entries before less-specific ones. Yes, RouteCollection is an ordered list, and the order in which you add route entries is critical to the routematching process.
I have a series of blog posts on Routing you can read here: http://haacked.com/tags/Routing/default.aspx
Also, the route debugger http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx is a useful tool for playing around with routing and understanding why a route you think should match is not matching.
BTW, Matthew Abbot is correct. You need to re-order the routes. Nazar's quote from Steven Sanderson's book has the reason why that's the case. Routing evaluates routes in order and the first one wins.
Here's the simple exercise I would have done to debug this situation. Looking at your request:
/My/All/p5
I would go through each route one at a time in my system and ask, "would it match?". The first route where the answer is yes is the one that will match. In your example, you can see that route is the first route. This is why Steven suggests putting more-specific routes first, so they match.
And the Route Debugger I mentioned earlier does this exercise for you. It shows you every route that would match a given request.
精彩评论