以下路線Page/View/Id
將轉到頁面控制器中的View
方法。我也想要以下路線:如何分隔具有相同路徑但做不同事情的路線?
/{page-title}
去同樣的方法。這讓我可以像以下網址:
http://www.mysite.com/This-Is-a-Page
如何配置這一點,考慮This-Is-a-Page
可能是控制器還?
以下路線Page/View/Id
將轉到頁面控制器中的View
方法。我也想要以下路線:如何分隔具有相同路徑但做不同事情的路線?
/{page-title}
去同樣的方法。這讓我可以像以下網址:
http://www.mysite.com/This-Is-a-Page
如何配置這一點,考慮This-Is-a-Page
可能是控制器還?
您也許能(缺省路由後,地方本)都加一抓,像這樣:
routes.MapRoute(
null,
"{*query}",
new { controller = "SomeController", action = "SomeAction" }
);
和動作的簽名是這樣的:
public ActionResult(string query)
如果兩個你的「控制器」路線和「頁面」路線(見下文)使用相同的/something
,那麼你將不得不實施以下規則:
在您的路線的頂部:
route. MapRoute(
"ControllerRoute"
"{controller}",
new { controller = "Home", action = "Index" }
new { controller = GetControllerNameRegex() }
);
route.MapRoute(
"PageRoute",
"{pageSlug}"
new { controller = "Page", action = "ShowPage" }
);
既然你不能真正做到以編程後者,但you can do the former programmatically,您可以添加自定義約束到控制器的路線,所以,它只會打,如果你碰巧鍵入控制器的名稱:
private static string GetControllerNameRegex()
{
var controllerNamesRegex = new StringBuilder();
List<string> controllers = GetControllerNames();
controllers.ForEach(s =>
controllerNamesRegex.AppendFormat("{0}|", s));
return controllerNamesRegex.ToString().TrimEnd('|');
}
private static List<Type> GetSubClasses<T>()
{
return Assembly.GetCallingAssembly().GetTypes().Where(type =>
type.IsSubclassOf(typeof(T))).ToList();
}
public List<string> GetControllerNames()
{
List<string> controllerNames = new List<string>();
GetSubClasses<Controller>().ForEach(type => controllerNames.Add(type.Name));
return controllerNames;
}
NB:最好的辦法是,以確保不會有你的控制器命名的任何頁面,你可以使用上面的代碼執行,在運行時。
這已經發布兩次是一樣的: http://stackoverflow.com/questions/2591524/asp-net-mvc-routes – 2010-04-07 10:16:19
我刪除了雙崗如果 – IceHeat 2010-04-07 10:17:03