[英]How to map a route for /News/5 to my news controller
我正在嘗試確定如何將/ 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
);
我嘗試去/ News / 5但是我收到了資源未找到錯誤,但是當進入/ News / Index / 5時它有效嗎?
我只試過{controller}/{id}
但這只是產生了同樣的問題。
謝謝!
您的{controller}/{id}
路由是正確的,但是您在另一條路線之后注冊了它。 在路線列表中,它自上而下搜索並找到匹配的第一個匹配。
為了幫助引導路由,我建議為此創建路由約束,以確保#1控制器存在,#2 {id}
是一個數字。
看到這篇文章
主要是:
routes.MapRoute(
"Index Action", // Route name
"{controller}/{id}", // URL with parameters EDIT: forgot starting "
new { controller = "News", action = "Index" },
new {id= @"\d+" }
);
您需要確保新路由在默認路由之前,如下所示:
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
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.