【问题标题】:How to get route url properties by route name using C# code?如何使用 C# 代码通过路由名称获取路由 url 属性?
【发布时间】:2013-10-12 12:27:03
【问题描述】:

我们知道,一个路由映射在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 }
    );
}

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

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

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

【问题讨论】:

  • 查看this questionRouteInfo 类提供基于 url 的路由信息​​。

标签: c# asp.net-mvc


【解决方案1】:

这是通过名称获取路线的方法:

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;
    // ...
}

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 2018-04-04
    • 2012-12-25
    • 1970-01-01
    • 2014-12-04
    • 2015-05-19
    • 1970-01-01
    • 2016-11-16
    • 2018-04-30
    相关资源
    最近更新 更多