我正在尝试从C#的Pascal格式重写URL到SEO友好的格式。
例如,我想是这样/User/Home/MyJumbledPageName
看起来像这样:如何在MapRoute方法中一般实现URL重写?
/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 }
);
}
有了这个代码,这样的URL /AboutTheAuthor
是不转换成我想要的东西,这将是/about-the-author
。
看来我的方法调用被忽略了,这里发生了什么?传统的实现方式是什么?
Thanks @LostInComputer!这对我来说有点远了,所以我一直在研究你的代码。我了解到您正在使用“空合并运算符”'''',其中三元运算符是速记。此外,我看到您正在使用在Route中调用'base'所需的构造函数参数,在Visual Studio中右键单击'Route'并选择“Peek Definition”。否则,你怎么知道重写'GetRouteData'和'GetVirtualPath'?框架中的哪些方法可以调用这些方法? –
我有的其他问题是'GetActualValue'方法是这个逻辑的一个要求,哪里是把这个类放在一个项目中的好地方? –
MVC调用'GetVirtualPath'来生成URL,就像调用'@ Html.Action'一样。 'GetRouteData'是相反的,它被MVC调用来从URL获取控制器动作。我怎么知道的?我有时会通过开源的MVC源代码。 – LostInComputer