【发布时间】:2014-01-06 05:57:59
【问题描述】:
我正在尝试将 URL 从 C# 的 Pascal-case 重写为对 SEO 友好的格式。
例如,我希望像 /User/Home/MyJumbledPageName 这样的东西看起来像这样:
/user/home/my-jumbled-page-name // lower-case, and words separated by dashes
这是我在 URL 中转换每个“令牌”的方法:
public static string GetSEOFriendlyToken(string token)
{
StringBuilder str = new StringBuilder();
for (int i = 0, len = token.Length; i < len; i++)
{
if (i == 0)
{
// setting the first capital char to lower-case:
str.Append(Char.ToLower(token[i]));
}
else if (Char.IsUpper(token[i]))
{
// setting any other capital char to lower-case, preceded by a dash:
str.Append("-" + Char.ToLower(token[i]));
}
else
{
str.Append(token[i]);
}
}
return str.ToString();
}
...在我的 RouteConfig.cs 根文件中,我映射了这些路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// without this the first URL is blank:
routes.MapRoute(
name: "Default_Home",
url: "index", // hard-coded?? it works...
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Home",
// the method calls here do not seem to have any effect:
url: GetSEOFriendlyToken("{action}") + "/" + GetSEOFriendlyToken("{id}"),
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
使用此代码,/AboutTheAuthor 等 URL 未 转换为我想要的,即 /about-the-author。
似乎我的方法调用被忽略了,这里发生了什么?实现这一点的传统方法是什么?
【问题讨论】:
标签: c# url-rewriting seo asp.net-mvc-routing