2012-02-17 51 views
13

我正在尝试识别如何将/ News/5的路由映射到我的新闻控制器。如何将/ News/5的路由映射到我的新闻控制器

这是我NewsController:

public class NewsController : BaseController 
{ 
    // 
    // GET: /News 

    public ActionResult Index(int id) 
    { 
     return View(); 
    } 

} 

这是我的Global.asax.cs规则:

 routes.MapRoute(
      "News", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "News", action = "Index", id = -1 } // Parameter defaults 
     ); 

我试着去/新闻/ 5,但是我收到一个未找到资源错误,但是当去/新闻/索引/ 5它的作品?

我刚才试过{controller}/{id}但这只是产生了同样的问题。

谢谢!

+2

当你试图'{控制器}/{id}'你是否保留默认操作? '新{控制器=“新闻”,行动=“索引”,编号= -1}' – Lazarus 2012-02-17 16:38:26

回答

18

{controller}/{id}您的{controller}/{id}路线是正确的,但您在另一条路线后注册了它。在路线列表中,它从上到下搜索并找到第一个匹配的胜利。

为了帮助引导路由,我建议为此创建路由约束,以确保#1控制器存在,#2 {id}是一个数字。

this article

主要是:

routes.MapRoute( 
     "Index Action", // Route name 
     "{controller}/{id}", // URL with parameters EDIT: forgot starting " 
     new { controller = "News", action = "Index" }, 
     new {id= @"\d+" } 
    ); 
+0

非常感谢,我不能接受你的消息8分钟,但我会回来。你用下面的约束来解决我的问题:'new {controller =“News”,id = @“0 | - ?[1-9] \ d *”} //路由限制,并将它移动到其他地图路线上方 – ElveMagicMike 2012-02-17 16:40:46

6

你需要确保你的新的路线是你默认路由之前,像这样:

routes.MapRoute(
     "NewsAbbr", // Route name 
     "{controller}/{id}", // URL with parameters 
     new { controller = "News", action = "Index", id = -1 } // Parameter defaults 
    ); 


    routes.MapRoute(
     "News", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "News", action = "Index", id = -1 } // Parameter defaults 
    );