Enum的ASP NET MVC3路由

Pau*_*bra 1 asp.net-mvc-routing asp.net-mvc-3

我通过允许格式的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
        );

}
Run Code Online (Sandbox Code Playgroud)

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

在一个理想的世界中,如果路径的第一部分中的值与ContentCategory枚举匹配(不区分大小写),则需要使用第一条路径,如果不匹配则使用默认路由.

这些类别很快就会发生变化所以这不是一件大事,但如果感觉应该是可能的话.

Uma*_*air 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);
}
Run Code Online (Sandbox Code Playgroud)