I need to create a url scheme like this
friend/{userid}/wishlist
开发者_运维技巧
where friend is the controller, wishlist is the view, and userid is the id of hte friend whose wishlist you would like to see.
I have setup a route like this
routes.MapRoute(
"FriendWishlist",
"friend/{userid}/wishlist",
new { controller = "WishList", action="FriendWishlist", userid = 123}
);
when i try to browse to /friend/123/wishlist
i get the following error
A public action method '123' was not found on controller 'GiffrWeb.Areas.Api.Controllers.FriendController'.
Routes in MVC are evaluated in the order they are declared. It sounds very much like you have declared your route below the default one:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"FriendWishlist",
"friend/{userid}/wishlist",
new { controller = "WishList", action="FriendWishlist", userid = 123}
);
So the MVC framework is trying to match your URL /friend/123/wishlist
first to the default route. Because it's all variables and everything has a default or is optional, it's guaranteed to match. It doesn't check if the controllers and actions exist and take the relevant arguments. You have a FriendController
class - check. 123
action - it goes bang.
Simplest fix - declare the route above the default one (ie just swap these two statements) and it should work OK.
I might just add that it seems a little weird to have a URL that starts with /friend/
going to a WishList controller when you obviously have a Friend controller (your error message says so).
Finally, I can't recommend highly enough that if you introduce custom routing that you also test those routes thoroughly - as you have seen, the routing engine often might not do what you think it does. I recommend either the route testing stuff in MvcContrib or Brad Wilson's blog post.
精彩评论