Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup complex routing in asp.net MVC

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.

like image 238
Micah Avatar asked Dec 12 '22 08:12

Micah


1 Answers

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
);
like image 85
counsellorben Avatar answered Dec 24 '22 05:12

counsellorben