2012-11-19 49 views
1

我已经设置了路由通过允许URL格式允许搜索引擎优化(和人类)友好的URL ~/{category}/{title}ASP NET MVC3路由通过枚举

所有的路由经过其中有一种方法,内容控制器适当重定向。我也想要允许~/{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和enum中我们有类别。

在理想世界中,如果路径的第一部分中的值与ContentCategory枚举相匹配(不区分大小写),并且默认路由不匹配,那么我会使用第一条路径。

这些类别将很少发生变化,所以这不是一件大事,但如果觉得它应该是可能的。

回答

10

对不起我的实际问题是什么略有困惑,但你可以通过实际的枚举生成正则表达式对象绕过“更改代码在两个地方”(排序):

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); 
} 
+0

这就是问题,看起来像答案 - brillog! –