2015-06-21 79 views
2

我需要帮助创建一个像MVC网站中的URL路由一样的永久链接。ASP .NET MVC,像路由配置一样创建永久链接

蛞蝓已经被设置为www.xyz.com/profile/{slug}:代码:

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 } 
      ); 

什么,我需要做到的是,你WordPress的永久链接或一把umbraco看到一个网址固定链接。我需要有www.xyz.com/{Slug}。

我曾尝试使用:

routes.MapRoute(
    name: "Profile", 
    url: "{slug}", 
    defaults: new { controller = "ctrlName", action = "actionName" } 
      ); 

但是,这并没有为我工作。

编辑:

如果我切换上面的路线CONFIGS中,嵌入功能的作品,但在常规路由不再一样。

这是否意味着我被迫在所有页面上实现永久链接功能?

+0

您是否有一个名为“ctrlName”的控制器,名为“actionName”的操作方法?如果是,则操作应该有一个名为“slug”的字符串参数。如果否,请在路由配置中设置正确的控制器和操作名称。 –

+0

我把ctrlName和actionName设置为slug作为字符串参数。就像我说的/ profile/{Slug}正在工作。但/ {Slug}不是。/{Slug}用于相同的ctrlName actionName。 –

+0

顺便说一下,例外情况是:HTTP 404.您正在查找的资源(或其某个依赖项)可能已被删除,名称已更改或暂时不可用。 –

回答

2

如果你想从根目录(site.com/{slug)获得永久链接,那么你可以使用你的slug路由。 但是对于任何其他控制器/操作的工作,您需要明确指定一个路径,以便在您的slu route路线上方。例如:

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" } 
); 

这应该工作;我已经完成了这个之前,但恐怕我从内存和VB回答。我在这个文本编辑器中将代码从VB转换为C#,所以我不能确定没有错误。

+0

谢谢你的回答,我已经解决了这个问题,但是你的答案应该可以工作。 –