MVC Routing without controller in the url

2019-04-06 23:19发布

问题:

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

回答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.



回答2:

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