Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Route Url to MVC controller action from WebAPI

Tags:

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?

like image 548
Kramer00 Avatar asked Mar 06 '13 14:03

Kramer00


People also ask

What class can be used to generate links to routes in Web API?

In the previous section, we learned that Web API can be configured in WebApiConfig class. Here, we will learn how to configure Web API routes. Web API routing is similar to ASP.NET MVC Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.

How can use route in MVC controller?

Configure a Route Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig. cs under App_Start folder. The following figure illustrates how to configure a route in the RouteConfig class .

How use Web API route?

In this article Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

Is it possible to have MVC kind of routing in Web API?

If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.


1 Answers

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" }); 
like image 89
RaghuRam Nadiminti Avatar answered Sep 25 '22 00:09

RaghuRam Nadiminti