How do I generate a URL outside of a controller in ASP.NET MVC?
How do I g开发者_如何学Goenerate a URL pointing to a controller action from a helper method outside of the controller?
You could use the following if you have access to the HttpContext
:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
You can use LinkGenerator . It's new feature in Microsoft.AspNetCore.Routing namespace and has been added in Aug 2020 .
At first you have to inject that in your class :
public class Sampleervice
{
private readonly LinkGenerator _linkGenerator;
public Sampleervice (LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
}
public string GenerateLink()
{
return _linkGenerator.GetPathByAction("Privacy", "Home");
}
}
For more information check this
Using L01NL's answer, it might be important to note that Action method will also get current parameter if one is provided. E.g:
editing project with id = 100
Url is http://hostname/Project/Edit/100
urlHelper.Action("Edit", "Project")
returns http://hostname/Project/Edit/100
while urlHelper.Action("Edit", "Project", new { id = (int?) null });
returns http://hostname/Project/Edit
Since you probably want to use the method in a View, you should use the Url
property of the view. It is of type UrlHelper
, which allows you to do
<%: Url.Action("TheAction", "TheController") %>
If you want to avoid that kind of string references in your views, you could write extension methods on UrlHelper
that creates it for you:
public static class UrlHelperExtensions
{
public static string UrlToTheControllerAction(this UrlHelper helper)
{
return helper.Action("TheAction", "TheController");
}
}
which would be used like so:
<%: Url.UrlToTheControllerTheAction() %>
Pass UrlHelper to your helper function and then you could do the following:
public SomeReturnType MyHelper(UrlHelper url, // your other parameters)
{
// Your other code
var myUrl = url.Action("action", "controller");
// code that consumes your url
}
精彩评论