您不需要失去默認路由。避免你的路線互相干擾的關鍵是要訂購它們,以便更具體的規則先於不太具體的規則。例如:
// Your specialized route
routes.MapRoute(
"Page",
"Page/{slug}",
new { controller = "Page", action = "Index" }
);
// Default MVC route (fallback)
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
那麼你的PageController應該是這樣的:
using System.Web.Mvc;
public class PageController : Controller
{
public string Index(string slug)
{
// find page by slug
}
}
這就是說,我會強烈建議你這樣做,而不是:
// Your specialized route
routes.MapRoute(
"Page",
"Page/{id}/{slug}",
new { controller = "Page", action = "Index", slug = UrlParameter.Optional }
);
// MVC's default route (fallback)
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
和你的PageController :
using System.Web.Mvc;
public class PageController : Controller
{
public string Index(int id)
{
// find page by ID
}
}
通過在頁面的開頭添加頁面ID(比如StackOverflow)或者在最後添加頁面ID,然後您可以忽略該段落,而是通過ID檢索您的頁面。如果用戶更改頁面名稱,這將爲您節省大量頭痛。我已經經歷了這一點,這是痛苦的;你基本上必須記錄你的網頁過去的所有名字,這樣你的訪問者/搜索引擎每次頁面重命名時都不會得到404。
希望這會有所幫助。
另外http://stackoverflow.com/questions/973205/asp-net-mvc-default-route – 2011-03-10 10:11:36