【问题标题】:ASP NET MVC3 Routing by Enum枚举的 ASP NET MVC3 路由
【发布时间】:2012-11-07 09:19:57
【问题描述】:

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

所有这些都应该路由到具有适当重定向方法的内容控制器。我还想允许 ~/{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 枚举匹配(不区分大小写),我希望使用第一个路由,如果不匹配,则使用默认路由。

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

【问题讨论】:

    标签: asp.net-mvc-3 asp.net-mvc-routing


    【解决方案1】:

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

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

    【讨论】:

    • 这就是问题所在,看起来也很像答案 - brillog!
    猜你喜欢
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    相关资源
    最近更新 更多