2014-09-03 70 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路由中,以查找没有任何参数的网址。