Set default action (instead of index) for controll

2019-02-16 07:36发布

问题:

I have a controller called Dashboard with 3 actions: Summary, Details, and Status, none of which take an ID or any other parameters. I want the URL /Dashboard to route to the Summary action of the Dashboard controller, as /Dashboard/Summary does, but I can't figure out the correct way to add the route. In Global.asax.cs, I have the following:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
    );

routes.MapRoute(
    "/Dashboard",
    "Dashboard",
    new { controller = "Dashboard", action = "Summary" }
    );

For the second part, I've also tried:

routes.MapRoute(
    "/Dashboard",
    "{controller}",
    new { controller = "Dashboard", action = "Summary" }
    );

and

routes.MapRoute(
    "/Dashboard",
    "{controller}",
    new { action = "Summary" }
    );

but I always get a 404 when trying to access /Dashboard. I'm pretty sure I'm missing something about the format for the parameters to MapRoute, but I don't know what it is...

回答1:

Move your Dashboard route in front of the Default route:

routes.MapRoute(
    "Dashboard",
    "Dashboard/{action}",
    new { controller = "Dashboard", action = "Summary" }
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);

The order of routes changes everything. Also, notice the changes I made to the Dashboard route. The first parameter is the name of the route. Second is the URL, which match URLs that start with Dashboard, and allows for other actions in your Dashboard controller. As you can see, it will default to the Summary action.



回答2:

You need to declare the "Default" catch-all route last.



回答3:

This set default Action for any Controller asp.net:

routes.MapRoute("Dashboard", "{controller}/{action}", 
defaults: new { controller = "Dashboard", action = "Summary" });