2014-09-03 66 views
0

我目前正嘗試按以下方式進行路由。先進的MVC.NET路由

  • /路線Home控制器,查看行動, 「家」 爲ID
  • /somePageId路線Home控制器,查看行動 「somePageId」 爲ID
  • /視頻路線到視頻控制器,索引動作
  • /Videos/someVideoName路由到視頻控制器,視頻動作與ID參數爲「someVideoName」
  • /新聞航線新聞控制器,索引操作
  • /新聞/ someNewsId路線消息控制器,查看行動 「someNewsId」 作爲id。

到目前爲止,我有以下代碼:

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" } 
); 

routes.MapRoute(
    name: "NewsIndex", 
    url: "News", 
    defaults: new { controller = "News", action = "Index" }, 
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" } 
); 

routes.MapRoute(
    name: "NewsView", 
    url: "News/{id}", 
    defaults: new { controller = "News", action = "_", id = UrlParameter.Optional }, 
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" } 
); 

routes.MapRoute(
    name: "PageShortCut", 
    url: "{id}", 
    defaults: new { controller = "Home", action = "_", id = UrlParameter.Optional }, 
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" } 
); 

,如果我去到/ home/_ /一下,我可以查看頁面,如果我去/一下,我剛剛得到一個404.

這是可能的mvc.net?如果是這樣,我會怎麼做呢?

+3

備註:樣本中的路線順序是向後的 - 默認路線可以匹配所有的路線,更具體的路線永遠不會被測試。確保在提出任何建議之前修正樣本以顯示合理的(最具體到最不具體的)路線順序。 – 2014-09-03 14:45:32

回答

1

嘗試從PageShortCut路徑中刪除UrlParameter.Optional。您也可能必須重新排序路線。

這對我的作品(作爲最後兩條路線):

routes.MapRoute(
    name: "PageShortCut", 
    url: "{id}", 
    defaults: new { controller = "Home", action = "_" }, 
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" } 
); 

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" } 
); 

而且我的控制器:

public class HomeController : Controller { 
    public string Index(string id) { 
     return "Index " + id; 
    } 

    public string _(string id) { 
     return id; 
    } 
} 

當你告訴路由引擎id是不可選的路徑,它除非id存在,否則不會使用該路線。這意味着該引擎將落入Default路由中,以查找沒有任何參數的網址。