0
我偶然發現了ASP.NET MVC路由中的奇怪行爲。在ASP.NET MVC路由錯誤4
在我RouteConfig文件,當我映射這樣的路徑(默認路徑):
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
使用:
@Html.ActionLink("Index", "Home")
我得到一個不錯的,乾淨的短網址,如: http://mysite/
但是,如果我添加其他可選參數id
後,像這樣:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
name = UrlParameter.Optional
}
);
同樣的ActionLink
每次輸出這個URL:http://mysite/home/index
。我使用RedirectToAction
驗證了相同的行爲。
我的問題是:有辦法解決這個問題,並在稍後的情況下獲得較短的URL?爲什麼ASP.NET MVC路由引擎在這些情況下表現不同?
編輯
我設法解決這個問題,下面我說我的自定義URL模式相匹配的「默認」路線之前添加了自定義路由發佈由Dave A.說明。
routes.MapRoute(
name: "Custom",
url: "{controller}/{action}/{id}/{name}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
你在哪裏渲染這些路線更「毛刺」?你總是冒險從/首頁/索引? – 2013-03-13 03:23:36
我嘗試了不同的動作/控制器,並且在這兩種情況下總是得到相同的結果。 – Meryovi 2013-03-13 03:30:52
MVC框架處理路線的方式確實存在「錯誤」或效率低下。在這種情況下,尤其是,它試圖充分利用所有參數,但卻感到困惑。閱讀這篇文章被黑客攻擊,顯示系統中更多的「小故障」http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx – 2013-03-13 03:41:04