【问题标题】:SEO friendly URLs with "-" [closed]带有“-”的 SEO 友好 URL [关闭]
【发布时间】:2023-06-10 18:22:01
【问题描述】:

我正在尝试解决对 seo 友好的网址的问题。以下是模板:

{city} 和 {area / District} 都可以包含多个单词,空格被替换为“-”符号。

这里有几个例子:

默认路由机制似乎没有解决这个问题。此外,还有一个 Html.RouteLink 功能可以很好地保留。

解决这个问题的最佳方法是什么?

PS:我知道使用“/{state}/{city}/”模式更容易,但我现在无法使用它。

【问题讨论】:

    标签: asp.net-mvc routes seo asp.net-mvc-routing


    【解决方案1】:

    很确定这种事情是用路由约束来处理的。

    这是一篇文章,显示了与您尝试做的类似的事情 http://www.codeproject.com/Articles/641783/Customizing-Routes-in-ASP-NET-MVC

    这也是一个处理相同问题的 SO 问题 ASP.NET MVC regex route constraint

    由于城市可以有导致多个破折号的空格,您可能必须走完整的路线来添加您自己的自定义约束(继承自 IRouteConstraint)然后在 match 方法中将 last 转换为字符并将它们转换为从那里你的状态。第一篇 codepoject 文章应该有一个自定义约束的示例。

    可能看起来像这样

    RouteConfig.cs

    public static void RegisterRoutes(RouteCollection routes)
    {
        //we're basically telling it to capture everything here with the {*customRoute},
        //then we're also passing that route to the Action
        routes.MapRoute("CityStates", "{*customRoute}",
            new { controller = "CityStateController", action = "MyAction", customRoute = UrlParameter.Optional},
            new { customRoute = new CityStateConstraint()});
    }
    

    CityStateConstraint.cs

    public class CityStateContraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
                RouteDirection routeDirection)
        {
            //return true if it is one of the city-states you handle
            //false otherwise
        }
    }
    

    在此示例中,路线将传递给您的操作,您可以处理从那里拆分城市和州...您可能希望使其分别通过城市和州,以便您的操作更清晰。但希望这能给你一个想法。

    也可以用一种更简单的方法来实现这一点,但必须由更熟悉 mvc 路由的人来参与。

    【讨论】:

    • 这是一个很好的方法。让我担心的是,如果我们开始添加更多路线,它会变得更加混乱。考虑以下示例:“{city}-{county}-{state}”、“{district/area}-{city}-{state}”、“{city}-{state}-{zip}”、等
    • 我正在寻找的另一件事是使用 Html.RouteLink 辅助方法来生成与路由兼容的 url。