如何使用C#代码通过路由名称获取路由URL属性?

时间:2013-10-05 15:17:10

标签: c# asp.net-mvc

众所周知,路由映射在Global.asax文件中,如:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

有一个方法/类,我可以通过提供路由名称来访问路由网址属性名称吗?

例如,对于Default,我想调用类似

的内容
public object[] GetRoutePropertiesByName(string name) {
    // process here the `controller`, `action`, `id` // there might be also other values
}

1 个答案:

答案 0 :(得分:2)

这是你如何按名称获得路线:

RouteTable.Routes[routeName]

从那里你可以获得一些路线属性:

var route = RouteTable.Routes[routeName] as Route;
if (route != null)
{
    var url = route.Url;        
    var controller = route.Defaults["controller"] as string;
    var action = route.Defaults["action"] as string;
    // ...
}