如何在 ASP.NET MVC 的控制器中获取路由名称? [英] How can I get the route name in controller in ASP.NET MVC?
问题描述
ASP.NET MVC 路由在映射时具有名称:
ASP.NET MVC routes have names when mapped:
routes.MapRoute(
"Debug", // Route name -- how can I use this later????
"debug/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = string.Empty } );
有没有办法获取路线名称,例如上面例子中的调试"?我想在控制器的 OnActionExecuting 中访问它,以便我可以在调试时在 ViewData 中设置内容,例如,通过在 URL 前加上/debug/...
Is there a way to get the route name, e.g. "Debug" in the above example? I'd like to access it in the controller's OnActionExecuting so that I can set up stuff in the ViewData when debugging, for example, by prefixing a URL with /debug/...
推荐答案
遗憾的是,路由名称未存储在路由中.它只是在 MVC 内部用作集合中的键.我认为这是您在使用 HtmlHelper.RouteLink 创建链接时仍然可以使用的东西(例如,也许在其他地方也是如此,不知道).
The route name is not stored in the route unfortunately. It is just used internally in MVC as a key in a collection. I think this is something you can still use when creating links with HtmlHelper.RouteLink for example (maybe somewhere else too, no idea).
无论如何,我也需要它,这就是我所做的:
Anyway, I needed that too and here is what I did:
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;
}
}
所以我可以注册一个这样的路由:
So I could register a route like this:
routes.MapRouteWithName(
"myRouteName",
"{controller}/{action}/{username}",
new { controller = "Home", action = "List" }
);
在我的控制器操作中,我可以通过以下方式访问路由名称:
In my Controller action, I can access the route name with:
RouteData.DataTokens["RouteName"]
希望有所帮助.
这篇关于如何在 ASP.NET MVC 的控制器中获取路由名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!