Call UrlHelper in models in ASP.NET MVC
I need to generate some URLs in a model in ASP.NET MVC. I'd like to call something li开发者_StackOverflow社区ke 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.
Is there any method I can call for that? Is there a way to construct an UrlHelper?
Helpful tip, in any ASP.NET application, you can get a reference of the current HttpContext
HttpContext.Current
which is derived from System.Web. Therefore, the following will work anywhere in an ASP.NET MVC application:
UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
url.Action("ContactUs"); // Will output the proper link according to routing info
Example:
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;
}
}
Calling the Link
property on a created MyModel object will return the valid Url to view the Model based on the routing in Global.asax
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);
A UrlHelper can be constructed from within a Controller action with the following:
var url = new UrlHelper(this.ControllerContext.RequestContext);
url.Action(...);
Outside of a controller, a UrlHelper can be constructed by creating a RequestContext from the RouteTable.Routes RouteData.
HttpContextWrapper httpContextWrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));
(Based on Brian's answer, with a minor code correction added.)
Yes, you can instantiate it. You can do something like:
var ctx = new HttpContextWrapper(HttpContext.Current);
UrlHelper helper = new UrlHelper(
new RequestContext(ctx,
RouteTable.Routes.GetRouteData(ctx));
RouteTable.Routes
is a static property, so you should be OK there; to get a HttpContextBase
reference, HttpContextWrapper
takes a reference to HttpContext
, and HttpContext
delivers that.
After trying all the other answers, I ended up with
$"/api/Things/Action/{id}"
Haters gonna hate ¯\_(ツ)_/¯
I was trying to do something similar from within a page (outside of a controller).
UrlHelper did not allow me to construct it as easily as Pablos answer, but then I remembered a old trick to effective do the same thing:
string ResolveUrl(string pathWithTilde)
Previous responses didn't help me. My approach has been create an action in my Home controller with the same functionality that UrlHelper.
[HttpPost]
[Route("format-url")]
public ActionResult FormatUrl()
{
string action = null;
string controller = null;
string protocol = null;
dynamic parameters = null;
foreach (var key in this.Request.Form.AllKeys)
{
var value = this.Request.Form[key];
if (key.Similar("action"))
{
action = value;
}
else if (key.Similar("controller"))
{
controller = value;
}
else if (key.Similar("protocol"))
{
protocol = value;
}
else if (key.Similar("parameters"))
{
JObject jObject = JsonConvert.DeserializeObject<dynamic>(value);
var dict = new Dictionary<string, object>();
foreach (var item in jObject)
{
dict[item.Key] = item.Value;
}
parameters = AnonymousType.FromDictToAnonymousObj(dict);
}
}
if (string.IsNullOrEmpty(action))
{
return new ContentResult { Content = string.Empty };
}
int flag = 1;
if (!string.IsNullOrEmpty(controller))
{
flag |= 2;
}
if (!string.IsNullOrEmpty(protocol))
{
flag |= 4;
}
if (parameters != null)
{
flag |= 8;
}
var url = string.Empty;
switch (flag)
{
case 1: url = this.Url.Action(action); break;
case 3: url = this.Url.Action(action, controller); break;
case 7: url = this.Url.Action(action, controller, protocol); break;
case 9: url = this.Url.Action(action, parameters); break;
case 11: url = this.Url.Action(action, controller, parameters); break;
case 15: url = this.Url.Action(action, controller, parameters, protocol); break;
}
return new ContentResult { Content = url };
}
Been an action, you can request it from anywhere, even inside the Hub:
var postData = "action=your-action&controller=your-controller";
// Add, for example, an id parameter of type integer
var json = "{\"id\":3}";
postData += $"¶meters={json}";
var data = Encoding.ASCII.GetBytes(postData);
#if DEBUG
var url = $"https://localhost:44301/format-url";
#else
var url = $"https://your-domain-name/format-url";
#endif
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/text/plain";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var link = new StreamReader(stream: response.GetResponseStream()).ReadToEnd();
You can get source code of AnonymousType here.
I think what you're looking for is this:
Url.Action("ActionName", "ControllerName");
精彩评论