我如何在ASP.NET MVC控制器获取路线名字? [英] How can I get the route name in controller in ASP.NET MVC?

查看:139
本文介绍了我如何在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的,例如,通过prefixing与/调试/...

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆