Mik*_*ott 53 model-view-controller asp.net-mvc routing
ASP.NET MVC路由在映射时具有名称:
routes.MapRoute(
"Debug", // Route name -- how can I use this later????
"debug/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = string.Empty } );
Run Code Online (Sandbox Code Playgroud)
有没有办法获取路由名称,例如上面的例子中的"Debug"?我想在控制器的OnActionExecuting中访问它,以便我可以在调试时在ViewData中设置内容,例如,通过在/ debug /前面添加一个URL ...
Nic*_*hac 74
遗憾的是,路径名称未存储在路径中.它仅在MVC内部用作集合中的键.我认为这是你在用HtmlHelper.RouteLink创建链接时仍然可以使用的东西(也许在其他地方,也不知道).
无论如何,我也需要它,这就是我所做的:
public static class RouteCollectionExtensions
{
public static Route MapRouteWithName(this RouteCollection routes,
string name, string url, object defaults, object constraints)
{
Route route = routes.MapRoute(name, url, defaults, constraints);
route.DataTokens = new RouteValueDictionary();
route.DataTokens.Add("RouteName", name);
return route;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以注册这样的路线:
routes.MapRouteWithName(
"myRouteName",
"{controller}/{action}/{username}",
new { controller = "Home", action = "List" }
);
Run Code Online (Sandbox Code Playgroud)
在我的Controller操作中,我可以使用以下命令访问路径名称:
RouteData.DataTokens["RouteName"]
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.