1

我已设置路由以通过允许格式为 URL 来允许 SEO(和人类)友好的 URL~/{category}/{title}

所有这些都应该路由到具有适当重定向方法的内容控制器。我还想允许~/{category}将您带到过滤索引。

所有这些都对我有用:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Category And Title", // Route name
        "{category}/{title}", // URL with parameters
        new { controller = "Content", action = "SeoRouting", title = UrlParameter.Optional }, // Parameter defaults
        new { category = "People|IT|Personnel|Finance|Procedures|Tools"}
        ); 

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
        );

}

但如果类别发生变化,那么我需要在两个地方进行更改。在 Global.asax 和枚举中,我们有类别。

在理想情况下,如果路径第一部分中的值与 ContentCategory 枚举匹配(不区分大小写),我希望使用第一条路由,如果不匹配,则使用默认路由。

类别将很少改变,所以这不是一件大事,但如果感觉它应该是可能的。

4

1 回答 1

12

抱歉,我对实际问题有点困惑,但是您可以通过使用实际枚举生成正则表达式对象来绕过“在两个地方更改代码”(有点):

routes.MapRoute(
    "Category And Title", // Route name
    "{category}/{title}", // URL with parameters
    new { controller = "Content", action = "SeoRouting", title = UrlParameter.Optional }, // Parameter defaults
    new { category = getCategories() }
    ); 

private static string getCategories()
{
     var categories = Enum.GetNames(typeof(ContentCategory));
     return string.Join("|", categories);
}
于 2012-11-19T12:49:58.493 回答