How do I generate a URL outside of a controller in

2020-06-06 17:24发布

问题:

How do I generate a URL pointing to a controller action from a helper method outside of the controller?

回答1:

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
}


回答2:

You could use the following if you have access to the HttpContext:

var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);


回答3:

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



回答4:

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() %>