【问题标题】:ASP .NET MVC, Creating a permalink like routing configurationASP .NET MVC,创建类似路由配置的永久链接
【发布时间】:2015-09-06 21:51:24
【问题描述】:

我需要帮助在 MVC 网站中创建诸如 URL 路由之类的永久链接。

Slug 已设置为 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 永久链接上看到的 URL。我需要 www.xyz.com/{Slug}。

我试过用:

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

但这对我不起作用。

编辑:

如果我切换上面的路由配置,slug 功能会起作用,但常规路由不再起作用。

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

【问题讨论】:

  • 你有一个名为“ctrlName”的控制器和一个名为“actionName”的动作方法吗?如果是,则操作应该有一个名为“slug”的字符串参数。如果否,请在您的路由配置中设置正确的控制器和操作名称。
  • 我将 ctrlName 和 actionName 设置为 slug 作为字符串参数。就像我说的 /profile/{Slug} 正在工作。但是 /{Slug} 不是。 /{Slug} 用于相同的 ctrlName actionName。
  • 顺便说一下,例外情况是:HTTP 404。您要查找的资源(或其依赖项之一)可能已被删除、更改名称或暂时不可用。
  • 如果你把你的“配置文件”路由(带有“/{slug}”的那个)放在默认路由之后,然后从默认路由中删除默认控制器和操作。这样,默认路由仍然适用于例如 url '/Home/Show' 并且配置文件路由应该匹配所有 '/xyz' url's。

标签: c# asp.net-mvc routes


【解决方案1】:

如果您想从根目录 (site.com/{slug}) 获取永久链接,那么您可以按原样使用您的 slug 路由。 但是对于任何其他控制器/动作的工作,您需要在您的 slug 路由之上为它们明确指定一个路由。例如:

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#,所以我不能确定没有错误。

【讨论】:

  • 感谢您的回答。我已经解决了这个问题,但你的答案肯定会奏效。谢谢
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 2011-05-02
  • 2012-09-23
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多