Get the VirtualPath From the Area, Controller and Action

浪子不回头ぞ 提交于 2019-12-11 23:22:37

问题


I was wondering how to get a URL given the area, controller and action names. So far all I have managed to come up with is:

var httpContext = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(httpContext);

if (routeData != null) {
    var virtualPath = routeData.Route.GetVirtualPath(new RequestContext(httpContext, routeData), new RouteValueDictionary(new { area = "Pages", controller = "Home", action = "Index" }));

    if (virtualPath != null) 
        newNode.Url = "~/" + virtualPath.VirtualPath;
}

However it does not work. I was wondering if someone could help.

Thanks


回答1:


Incase anyone is wondering, here's the solution I have come up with:

// Set the context
var context = new RequestContext(new HttpContextWrapper(HttpContext.Current),
    new RouteData());
var urlHelper = new UrlHelper(context);

// Set the url
var url = urlHelper.Action("Index", "Home",
    new RouteValueDictionary(new { area = "Pages" }));

I hope this helps someone.



来源:https://stackoverflow.com/questions/8349452/get-the-virtualpath-from-the-area-controller-and-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!