165

我需要在 ASP.NET MVC 的模型中生成一些 URL。我想调用类似 UrlHelper.Action() 的东西,它使用路由来生成 URL。我不介意填写通常的空白,例如主机名、方案等。

有什么方法可以调用吗?有没有办法构造一个 UrlHelper?

4

7 回答 7

282

有用的提示,在任何 ASP.NET 应用程序中,您都可以获得当前 HttpContext 的引用

HttpContext.Current

它源自 System.Web。因此,以下内容可以在 ASP.NET MVC 应用程序中的任何地方工作:

UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
url.Action("ContactUs"); // Will output the proper link according to routing info

例子:

public class MyModel
{
    public int ID { get; private set; }
    public string Link
    {
        get
        {
            UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
            return url.Action("ViewAction", "MyModelController", new { id = this.ID });
        }
    }

    public MyModel(int id)
    {
        this.ID = id;
    }
}

在创建的 MyModel 对象上调用Link属性将返回有效的 Url 以根据 Global.asax 中的路由查看模型

于 2010-01-09T02:42:35.580 回答
69

我喜欢奥马尔的回答,但这对我不起作用。仅作记录,这是我现在使用的解决方案:

var httpContext = HttpContext.Current;

if (httpContext == null) {
  var request = new HttpRequest("/", "http://example.com", "");
  var response = new HttpResponse(new StringWriter());
  httpContext = new HttpContext(request, response);
}

var httpContextBase = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContextBase, routeData);

return new UrlHelper(requestContext);
于 2010-01-09T03:32:45.387 回答
49

UrlHelper 可以从 Controller 操作中构造,具有以下内容:

 var url = new UrlHelper(this.ControllerContext.RequestContext);
 url.Action(...);

在控制器之外,可以通过从 RouteTable.Routes RouteData 创建 RequestContext 来构造 UrlHelper。

HttpContextWrapper httpContextWrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));

(基于布赖恩的回答,添加了一个小的代码更正。)

于 2010-01-09T02:04:20.287 回答
8

是的,您可以实例化它。您可以执行以下操作:

var ctx = new HttpContextWrapper(HttpContext.Current);
UrlHelper helper = new UrlHelper(
   new RequestContext(ctx,
   RouteTable.Routes.GetRouteData(ctx));

RouteTable.Routes是一个静态属性,所以你应该没问题;获取HttpContextBase引用,HttpContextWrapper获取对 的引用HttpContext,然后HttpContext传递它。

于 2010-01-09T02:14:26.600 回答
4

在尝试了所有其他答案之后,我最终得到了

$"/api/Things/Action/{id}"

讨厌的人会讨厌¯\_(ツ)_/¯

于 2018-03-09T14:58:43.727 回答
0

我试图从页面内(控制器外部)做类似的事情。

UrlHelper 不允许我像 Pablos 回答那样轻松地构建它,但后来我想起了一个有效地做同样事情的老技巧:

string ResolveUrl(string pathWithTilde)
于 2015-02-17T15:39:57.157 回答
-30

我认为您正在寻找的是:

Url.Action("ActionName", "ControllerName");
于 2010-01-09T02:03:17.400 回答