在 ASP.NET MVC 中的模型中调用 UrlHelper [英] Call UrlHelper in models in ASP.NET MVC

查看:25
本文介绍了在 ASP.NET MVC 中的模型中调用 UrlHelper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to generate some URLs in a model in ASP.NET MVC. I'd like to call something like UrlHelper.Action() which uses the routes to generate the URL. I don't mind filling the usual blanks, like the hostname, scheme and so on.

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

Is there any method I can call for that? Is there a way to construct an UrlHelper?

推荐答案

我喜欢 Omar 的回答,但这对我不起作用.只是为了记录,这是我现在使用的解决方案:

I like Omar's answer but that's not working for me. Just for the record this is the solution I'm using now:

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);

这篇关于在 ASP.NET MVC 中的模型中调用 UrlHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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