Will
Will

Reputation: 321

How to create url for MVC action from ApiController?

Is there a way to create an url that liks to an MVC action from an ApiController? I see examples of doing this the other way around, to reach ApiController from with MVC using MVC's UrlHelper (http://blogs.msdn.com/b/roncain/archive/2012/07/17/using-the-asp-net-web-api-urlhelper.aspx).

Any help would be greatly appreciated. Thanks.

Upvotes: 6

Views: 3845

Answers (1)

Jace Rhea
Jace Rhea

Reputation: 5018

You can use the Url property on the API controller to find a route to a web api or an MVC controller. Here is an example of creating a link to the default project template MVC method AccountController.Login(string returnURL).

    public class SOExampleController : ApiController
{

    public SOExample GetSOExample()
    {
        var url = Url.Route("Default", new {controller = "Account", action = "Login", returnUrl = "hello"});
        return new SOExample{URL = url};
    }
}

public class SOExample
{
    public string URL {get;set;}
}

When ran you get the url value of the "/Account/Login?returnUrl=hello". It looks like you may need to prepend the domain, which should be trivial to find.

Upvotes: 6

Related Questions