Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Routing without controller in the url

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
like image 780
Victoria Avatar asked May 18 '11 15:05

Victoria


1 Answers

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.

like image 178
NerdFury Avatar answered Sep 28 '22 07:09

NerdFury