2

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 }
    );

1 Answer 1

3

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/

2
  • Had to remove the headers (name: url: etc...) + missing comma after " defaults: new { controller = "Profile", action = "Show" }" But otherwise works as intended. Commented Nov 15, 2015 at 7:27
  • How do u do the same thing in .net 5 am trying to do the same using endpoints. Commented Mar 11, 2021 at 10:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.