如何从路径名称中检索控制器和操作名称?

时间:2012-07-07 15:16:17

标签: c# asp.net-mvc asp.net-mvc-routing

注册路由后,如何检索属于指定路由名称的控制器和操作名称?

例如,如果我注册这条路线:

routes.MapRoute("Category",
                "C/{id}/{urlText}",
                new { controller = "Catalog", action = "ProductListByCategoryId" }
);

我想通过路径名参数“Category”检索控制器名称“Catalog”和动作名称“ProductListByCategoryId”。

我需要这个用于html帮助器:

public static MvcHtmlString MenuLink(this HtmlHelper helper,
                                string name,
                                string routeName,
                                object routeValues)
{
    string currentAction = helper.ViewContext.RouteData.GetRequiredString("action");
    string currentController = helper.ViewContext.RouteData.GetRequiredString("controller");
    object currentId = helper.ViewContext.RouteData.Values["id"];

    string actionName = ""; //This is what I want to specify
    string controllerName = "";  //This is what I want to specify
    var propertyInfo = routeValues.GetType().GetProperty("id");
    var id = propertyInfo.GetValue(routeValues, null);

    if (actionName == currentAction &&
        controllerName == currentController &&
        id == currentId)
    {
        return helper.RouteLink(name, routeName, routeValues, new { @class = "active" });
    }
    else
    {
        return helper.RouteLink(name, routeName, routeValues, new { @class = "active" });
    }

}

1 个答案:

答案 0 :(得分:1)

仅给出路线名称不能这样做。原因是路由可以匹配多个控制器和操作。您可以做的是从HttpContext

中检索当前控制器和操作
RouteData rd = HttpContext.Request.RequestContext.RouteData;
string currentController = rd.GetRequiredString("controller");
string currentAction = rd.GetRequiredString("action");