ASP .NET MVC, Creating a permalink like routing configuration

故事扮演 提交于 2021-01-27 18:33:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!