8

How do I configure ASP.NET MVC 3 routing so it doesn’t shown the controller in the url?

Here's my routes

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

        routes.MapRoute(
            "HomeActions", 
            "{action}", 
            new { action= "AboutUs" } 
        );

I need url:

mysite.com/AboutUs

But I have

 mysite.com/Home/AboutUs

2 Answers 2

21

I would be very specific about the url that you want to route. And place it above the default route.

    routes.MapRoute(
        "HomeActions", 
        "AboutUs", 
        new { controller = "Home", action= "AboutUs" } 
    );

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

Being less specific with a route like the one you suggested might have unwanted consequences. Especially if listed below the default route.

routes.MapRoute(
    "HomeActions", 
    "{action}", 
    new { controller = "Home", action= "AboutUs" } 
);

For example, if the above route is added after the default then the url http://www.example.com/AboutUs would likely match the route {controller = "AboutUs", action = "Index", id = UrlParamter.Optional}. If you added the route above the default one, then looking for the url http://www.example.com/Users which you might want to be the Index action on the Users controller would now look for the Users action on the Home controller.

So, I would advise being specific about routes like that.

1
  • 1
    "And place it above the default route" helped, thanks
    – hawbsl
    Commented Nov 30, 2018 at 16:10
6

You need to add a route without the {controller} portion, and specify the controller name in the defaults parameter.

3
  • Not a wrong answer, but could be more specific. Hiding the controller name can have consequences.
    – NerdFury
    Commented May 18, 2011 at 15:36
  • Thanks for your answer, but it dosen't work. I try: routes.MapRoute( "HomeActions","{action}", new { controller="Home" } );
    – Victoria
    Commented May 18, 2011 at 15:36
  • @Victoria: You need to put that before the other route, or it will never be reached (since the other route matches URLs first)
    – SLaks
    Commented May 18, 2011 at 15:47

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.