问题
I need help crating a permalink like URL routing in a MVC website.
The Slugs are already set up as www.xyz.com/profile/{slug}: the code is:
routes.MapRoute(
name: "Profile",
url: "profile/{slug}",
defaults: new { controller = "ctrlName", action = "actionName" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What i need to achieve is a URL that you see on Wordpress permalinks or Umbraco permalinks. I need to have www.xyz.com/{Slug}.
I have tried to use:
routes.MapRoute(
name: "Profile",
url: "{slug}",
defaults: new { controller = "ctrlName", action = "actionName" }
);
But that did not work for me.
EDIT:
If I switch the route configs above, the slug functionality works but the regular routing no longer does.
Does that mean that I am forced to implement permalink functionality on all pages?
回答1:
If you want to have permalinks picked up from the root (site.com/{slug}) then you can use your slug route as is. But for any other controllers/actions work you'll need to explicitly specify a route for them ABOVE your slug route. Eg:
routes.MapRoute(
name: "Services",
url: "Services/{permalink}/",
defaults: new { controller = "Page", action = "Services"}
);
routes.MapRoute(
name: "Requests",
url: "Requests/{action}/{id}",
defaults: new { controller = "Requests", action = "Index", area = "" },
namespaces: new String() {"ProjectNamespace.Controllers"}
);
routes.MapRoute(
name: "AdminPreferences",
url: "Admin/Preferences",
defaults: new { controller = "Preferences", action = "Index", area = "Admin"},
namespaces: new String() {"ProjectNamespace.Areas.Admin.Controllers"}
);
...
routes.MapRoute(
name: "Profile",
url: "{slug}",
defaults: new { controller = "ctrlName", action = "actionName" }
);
This should work; I've acomplished this before but I'm afraid I'm answering from memory and VB. I converted the code from VB to C# in this text editor, so I can't be sure there isn't an error.
来源:https://stackoverflow.com/questions/30963113/asp-net-mvc-creating-a-permalink-like-routing-configuration