您不需要丢失默认路由。避免您的路线相互干扰的关键是对它们进行排序,以便更具体的规则优先于不太具体的规则。例如:
// 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
}
}
通过在 URL 的开头(如 StackOverflow)或末尾包含页面 ID,您可以忽略 slug,而是按 ID 检索您的页面。如果您的用户更改页面名称,这将为您省去很多麻烦。我经历过这很痛苦;您基本上必须记录您的页面过去使用的所有名称,这样您的访问者/搜索引擎就不会在每次重命名页面时都收到 404。
希望这会有所帮助。