I'm looking to setup routes that conform to these patterns:
/users
Mapped to action GetAllUsers()
/users/12345
Mapped to action GetUser(int id)
/users/1235/favorites
mapped to action GetUserFavorites(int id)
The controller should always be the UsersController. I thought that this would work, but it's not.
routes.MapRoute("1",
"{controller}/{action}/{id}",
new { id = UrlParameter.Optional, action = "index" });
routes.MapRoute("2",
"{controller}/{id}/{action}");
I'm struggling to wrap my head around it. Any help would be much appreciated.
To accomplish your goal, you would need three separate routes in RegisterRoutes
in global.asax.cs, which should be added in the following order, and must be before the Default
route (this assumes that id must be an integer):
routes.MapRoute(
"GetUserFavorites", // Route name
"users/{id}/favorites", // URL with parameters
new { controller = "Users", action = "GetUserFavorites" }, // Parameter defaults
new { id = @"\d+" } // Route constraint
);
routes.MapRoute(
"GetUser", // Route name
"users/{id}", // URL with parameters
new { controller = "Users", action = "GetUser" } // Parameter defaults
new { id = @"\d+" } // Route constraint
);
routes.MapRoute(
"GetAllUsers", // Route name
"users", // URL with parameters
new { controller = "Users", action = "GetAllUsers" } // Parameter defaults
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With