2011-11-07 103 views
3

假設我有一個新的MVC站點,並且我想按照以下方式實現URL。從路由角度來看,有什麼想法可以做到這一點?我會將帖子存儲在基本的數據庫表中。我想從控制器/操作角度儘可能地簡化它。通過路由的ASP.NET MVC博客URL

/2011 /(全部來自2011個)

/2011/11/

/2011/11/07

(全部來自2011年11月7日公告)(全部來自2011年11月公告)

/2011/11/07 /確切-後標題

/確切-後標題

/約

/歸檔

/標籤/任何標籤

回答

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

有幾分與/確切的標題後路線的問題。這將匹配你發送的任何東西。爲了解決這個問題,你必須把所有可能的路線放在那個前面。你也可以只前綴的所有這些路線與/或博客/文章,以解決它:

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

現在,它不會與下列衝突:

routes.MapRoute(
    "About", 
    "about", 
    new { controller = "Home", action = "About" } 
); 

存檔是相似的:

routes.MapRoute(
    "Archive", 
    "archive", 
    new { controller = "Home", action = "Archive" } 
); 

最後標籤路線:

routes.MapRoute(
    "Tag", 
    "tag/{tagtext}", 
    new { controller = "Tag", action = "Index" } 
); 

您可能需要隨路線的順序,但總體而言,您總是首先需要最具體的路線。

如果你有以下途徑:

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

routes.MapRoute(
    "About", 
    "about", 
    new { controller = "Home", action = "About" } 
); 

第一路由匹配/約所以你要去,如果他們是在爲遇到問題。

4

我的解決辦法是這樣的:

在RouteConfig.cs首先包括

  routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     **routes.MapMvcAttributeRoutes();** this is very important 
     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 

在你的控制器動作包括您需要的路線之後:

[Route("Posts/{year}/{month}/{day}/{title}")] 
    public ActionResult Post(int year, int month, int day, string title) 
    { 
     return View(); 
    } 

    [Route("Posts/{year}/{month}/{day}")] 
    public ActionResult Post(int year, int month, int day) 
    { 
     return View(); 
    } 

    [Route("Posts/{year}/{month}")] 
    public ActionResult Post(int year, int month) 
    { 
     return View(); 
    } 

    [Route("Posts/{yearOrTitle}")] 
    public ActionResult Post(string yearOrTitle) 
    { 
//logical to search year or Title 
     return View(); 
    }