问题
I have a controller action as you can see below:
public ActionResult Content(string slug)
{
var content = contentRepository.GetBySlug(slug);
return View(content);
}
I want this kind of urls to be routed to my action:
http://localhost/slug-of-my-content
Here is my RegisterRoutes method:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Page", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "GetContent",
url: "{slug}",
defaults: new { controller = "Page", action = "Content", slug = "" }
);
}
But it does not work, what am I doing wrong?
Thanks,
回答1:
1 put the slug route above default route,if not ,it never go the slug route
2 you slug can not be empty,if empty ,the url will be http://localhost/ it must go default route
routes.MapRoute(
name: "slug",
url: "{slug}",
defaults: new { controller = "Home", action = "show" },
constraints: new{ slug=".+"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
and i think don't pick "Content" as action name,becuse there is a Content Method in base class
回答2:
for dynamic routes, you could use:
routes.MapRoute(
name: "PageName",
url: "{pageName}",
defaults: new { controller = "Page", action = "Content", pageName = "defaultPage" }
);
which will map to ~/Pagename with the Action "Content" in the "Page" controller:
public ActionResult Content(string pageName)
{
ViewBag.Message = pageName;
return View();
}
来源:https://stackoverflow.com/questions/31606522/routing-by-slug-in-asp-net-mvc