Asp.Net: Removing the action name from the URL

I am trying to create a routing rule that allows me to use

http://localhost:*****/Profile/2

instead of

http://localhost:*****/Profile/Show/2

to access a page. I currently have a routing rule that successfully removes index when accessing a page. How do I apply the same concept to this?

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I have a couple of questions to clarify what you are trying to do. Because there could be some unintended consequences to creating a custom route.

1) Do you only want this route to apply to the Profile controller?

Try adding this route before the default route..

   routes.MapRoute(
        name: "Profile",
        url: "Profile/{id}",
        defaults: new { controller = "Profile", action = "Show" }

        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

This new route completely gets rid of the Index and other actions in the Profile controller. The route also only applies to the Profile controller, so your other controllers will still work fine.

You can add a regular expression to the “id” definition so that this route only gets used if the id is a number as follows. This would allow you to use other actions in the Profile controller again as well.

   routes.MapRoute(
        name: "Profile",
        url: "Profile/{id}",
        defaults: new { controller = "Profile", action = "Show" }
        defaults: new { id= @"d+" }
        );

Also, it would be a good idea to test various urls to see which route would be used for each of the urls. Go to NuGet and add the “routedebugger”
package. You can get information on how to use it at http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx/


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x