我需要在 ASP.NET MVC 的模型中生成一些 URL。我想调用类似 UrlHelper.Action() 的东西,它使用路由来生成 URL。我不介意填写通常的空白,例如主机名、方案等。
有什么方法可以调用吗?有没有办法构造一个 UrlHelper?
我需要在 ASP.NET MVC 的模型中生成一些 URL。我想调用类似 UrlHelper.Action() 的东西,它使用路由来生成 URL。我不介意填写通常的空白,例如主机名、方案等。
有什么方法可以调用吗?有没有办法构造一个 UrlHelper?
有用的提示,在任何 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 中的路由查看模型
我喜欢奥马尔的回答,但这对我不起作用。仅作记录,这是我现在使用的解决方案:
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);
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)));
(基于布赖恩的回答,添加了一个小的代码更正。)
是的,您可以实例化它。您可以执行以下操作:
var ctx = new HttpContextWrapper(HttpContext.Current);
UrlHelper helper = new UrlHelper(
new RequestContext(ctx,
RouteTable.Routes.GetRouteData(ctx));
RouteTable.Routes
是一个静态属性,所以你应该没问题;获取HttpContextBase
引用,HttpContextWrapper
获取对 的引用HttpContext
,然后HttpContext
传递它。
在尝试了所有其他答案之后,我最终得到了
$"/api/Things/Action/{id}"
讨厌的人会讨厌¯\_(ツ)_/¯
我试图从页面内(控制器外部)做类似的事情。
UrlHelper 不允许我像 Pablos 回答那样轻松地构建它,但后来我想起了一个有效地做同样事情的老技巧:
string ResolveUrl(string pathWithTilde)
我认为您正在寻找的是:
Url.Action("ActionName", "ControllerName");