[英]Advanced MVC.NET Routing
我目前正在嘗試以以下方式進行路由。
到目前為止,我有以下代碼:
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 / _ / About,我可以查看該頁面,如果我轉到/ About,我只會得到404。
在mvc.net中可以嗎? 如果是這樣,我將如何處理?
嘗試從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
,否則它將不會使用該路由。 這意味着對於沒有任何參數的URL,引擎將陷入Default
路由。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.