问题
I m trying to achive route like that:
http://mysite.com/portfolio/landscape
http://mysite.com/portfolio/friends etc...
so I wrote that:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"DefaultIndex", // Route name
"{controller}/{id}", // URL with parameters
new { action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
It works well I can have my route /portfolio/landscape but my Account controler that have SignIn, SignOut, Index actions doesn't work because it gets redirected to Index each time.
is it possible to get both?
Thank you by advance
回答1:
Try to introduce a constraint in your custom route otherwise it won't allow default route to be found.
routes.MapRoute(
"DefaultIndex", // Route name
"portfolio/{id}", // URL with parameters
new { controller="portfolio", action = "Index", id = UrlParameter.Optional }
);
This way you only map URLs starting with "portfolio" in your route, and specify which controller and action. Requests for other URLs are handled by the default route.
回答2:
I think you can just reverse the order of route declaration.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"DefaultIndex", // Route name
"{controller}/{id}", // URL with parameters
new { action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
If you mention any Controller and action it will go to that else it will pick the default
回答3:
Assuming there is a good reason for the existing routes, here is one way to make AccountController
play nice with those:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Account", // Account name
"account/{action}/{id}", // URL with parameters
new { controller = "Account", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"DefaultIndex", // Route name
"{controller}/{id}", // URL with parameters
new { action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
来源:https://stackoverflow.com/questions/9495277/mvc-route-with-default-action-and-parameter-several-actions-by-controller