MVC Routing without controller in the url

14,640

Solution 1

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.

Solution 2

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

Share:
14,640
Victoria
Author by

Victoria

Updated on June 04, 2022

Comments

  • Victoria
    Victoria almost 2 years

    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
    
  • encore2097
    encore2097 almost 13 years
    Not a wrong answer, but could be more specific. Hiding the controller name can have consequences.
  • Victoria
    Victoria almost 13 years
    Thanks for your answer, but it dosen't work. I try: routes.MapRoute( "HomeActions","{action}", new { controller="Home" } );
  • SLaks
    SLaks almost 13 years
    @Victoria: You need to put that before the other route, or it will never be reached (since the other route matches URLs first)
  • hawbsl
    hawbsl over 5 years
    "And place it above the default route" helped, thanks