从区域,控制器和操作获取虚拟路径 [英] Get the VirtualPath From the Area, Controller and Action

查看:137
本文介绍了从区域,控制器和操作获取虚拟路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在给定区域,控制器和动作名称的情况下获取URL.到目前为止,我只能想出的是:

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.

谢谢

推荐答案

万一有人想知道,这是我想出的解决方案:

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.

这篇关于从区域,控制器和操作获取虚拟路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆