21

I'm used to generating route URLs to other controller actions within an MVC controller action using something similar to below:

public class ApplicationController : Controller
{
    public ActionResult Index( )
    {
        var url = Url.RouteUrl("routename",
           new { controller = "Application", Action = "Index2" , other="other" });
    }

    public ActionResult Index2( string other)
    {
    }
}

But I also need to be able to generate URLs to MVC controller actions from within webapi too, How would I go about doing this?

There seems to be a UrlHelper property on the APIController but I cant find any examples of how to use this and have not been able to figure it out myself.

UPDATE : The reason I am trying to generate a url is that this particular webapi method sends an email which provides the recipient with a link to direct the user back to an appropriate section of the site. I obviously want to get away from hardcoding this as it will not work for different deployments and also if I begin changing the routing this link will be broken. Is there a better approach to doing this?

sharptooth
  • 167,383
  • 100
  • 513
  • 979
Kramer00
  • 1,167
  • 3
  • 12
  • 34

1 Answers1

28

You can use MVC route names as well with web API UrlHelper. Example,

 Url.Link("Default", new { Controller = "Account", Action = "Login" });

or

 Url.Route("Default", new { Controller = "Account", Action = "Login" });
RaghuRam Nadiminti
  • 6,718
  • 1
  • 33
  • 30
  • @TrueBlueAussie you're looking at the wrong UrlHelper. Look at the http one not the mvc one. – Steve Feb 12 '14 at 18:58
  • 1
    http://msdn.microsoft.com/en-us/library/system.web.http.routing.urlhelper_methods(v=vs.118).aspx. If you are using attribute routing, name your routes. – Steve Feb 12 '14 at 19:04
  • 1
    Are we sure this is possible? I get 'A route named '...' could not be found' exception and this question suggests it cannot be done: http://stackoverflow.com/questions/29147486/mvc-routes-within-webapi-controller – Tito Oct 05 '15 at 15:06