How to configure complex routing in asp.net MVC

I am looking for route settings that match 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 must always be a UserController. I thought this would work, but it is not.

 routes.MapRoute("1", "{controller}/{action}/{id}", new { id = UrlParameter.Optional, action = "index" }); routes.MapRoute("2", "{controller}/{id}/{action}"); 

I'm struggling to circle my head. Any help would be greatly appreciated.

+4
source share
2 answers

To achieve your goal, you will need three separate routes in RegisterRoutes in global.asax.cs, which must be added in the following order and must be before the Default route (this assumes the identifier 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 ); 
+10
source

advsellorben got the answer before I did. If you need these exact URLs and those exact methods, this is the only way. You can reduce the number of routes by combining GetUser and GetAllUsers in one action with a null identifier, for example.

 routes.MapRoute( "GetUser", "users/{id}", new { controller = "Users", action = "GetUser", id = UrlParameter.Optional} new { id = @"\d+" } // Route constraint ); 

To call the GetUser(int? id) method

If you want to use the URL to automatically start the controller and action, you will need something like

  routes.MapRoute( "GetUser", "{controller}/{action}/{id}", new { id = UrlParameter.Optional} new { id = @"\d+" } // Route constraint ); 

But for this you need to change the URLs you need so that /users/getuser/1234 GetUser(int id) to GetUser(int id) and /users/getallusers to GetAllUsers() . This is untested, by the way, there may be some minor errors.

+3
source

Source: https://habr.com/ru/post/1379681/


All Articles