Get the VirtualPath From the Area, Controller and

2019-08-29 12:42发布

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条回答
Emotional °昔
2楼-- · 2019-08-29 13:24

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.

查看更多
登录 后发表回答