通过路由的ASP.NET MVC博客URL

ahe*_*ick 3 asp.net-mvc blogs asp.net-mvc-routing

假设我有一个新的MVC站点,我想以下列方式实现URL.从路由角度来看,最好的方法是什么?我将帖子存储在基本数据库表中.我想从控制器/动作的角度尽可能简单地保持它.

/ 2011 /(2011年所有帖子)

/ 2011/11 /(2011年11月起的所有帖子)

/ 2011/11/07(2011年11月7日起的所有帖子)

/ 2011/11/07/EXACT-后称号

/确切-后称号

/关于

/存档

/标签/任何标签

Dis*_*ile 7

// matches /2011/11/07/exact-post-title
routes.MapRoute(
    "ArticleDetails",
    "{yyyy}/{mm}/{dd}/{title}",
    new { controller = "Articles", action = "Details",
    new { yyyy = @"(19|20)\d\d.", mm = @"\d\d", dd = @"\d\d" }
);

// matches /2011/11/07
routes.MapRoute(
    "ArticlesByDay",
    "{yyyy}/{mm}/{dd}",
    new { controller = "Articles", action = "ByDay",
    new { yyyy = @"(19|20)\d\d.", mm = @"\d\d", dd = @"\d\d" }
);

// matches /2011/11
routes.MapRoute(
    "ArticlesByMonth",
    "{yyyy}/{mm}",
    new { controller = "Articles", action = "ByMonth",
    new { yyyy = @"(19|20)\d\d.", mm = @"\d\d" }
);

// matches /2011
routes.MapRoute(
    "ArticlesByYear",
    "{yyyy}",
    new { controller = "Articles", action = "ByYear",
    new { yyyy = @"(19|20)\d\d." }
);
Run Code Online (Sandbox Code Playgroud)

/ exact-post-title路线存在一些问题.这几乎与你发送的东西相匹配.你必须把所有其他可能的路线放在那个路线前面才能解决这个问题.您也可以使用/ blog或/ articles为所有这些路由添加前缀以修复它:

routes.MapRoute(
    "ExactPostTitle",
    "articles/{title}", 
    new { controller = "Articles", action = "Details" }
);
Run Code Online (Sandbox Code Playgroud)

现在它不会与以下内容发生冲突:

routes.MapRoute(
    "About",
    "about",
    new { controller = "Home", action = "About" }
);
Run Code Online (Sandbox Code Playgroud)

档案将类似:

routes.MapRoute(
    "Archive",
    "archive",
    new { controller = "Home", action = "Archive" }
);
Run Code Online (Sandbox Code Playgroud)

最后是Tag路线:

routes.MapRoute(
    "Tag",
    "tag/{tagtext}",
    new { controller = "Tag", action = "Index" }
);
Run Code Online (Sandbox Code Playgroud)

您可能需要使用路线的顺序,但一般情况下,您始终需要最具体的路线.

如果您有以下路线:

routes.MapRoute(
    "ExactTitle",
    "{title}",
    new { controller = "Articles", action = "Details" }
);

routes.MapRoute(
    "About",
    "about",
    new { controller = "Home", action = "About" }
);
Run Code Online (Sandbox Code Playgroud)

第一条路线匹配/约会,所以如果它们按顺序排列会遇到问题.