OdeToCode IC Logo

WebAPI Tip #5: Generating Links

Wednesday, March 27, 2013

Generating a link to an ApiController isn't too difficult once you know the right methods to call.

Outside the API Controller

In a Razor view, for example, you can generate a link to an API controller using the standard Url helper property. The following link will point to an Albums controller and pass along an id parameter with a value of 3:

@Url.RouteUrl("DefaultApi", new { httproute=true, controller="Albums", id=3})

Notice the route name is "DefaultApi", which is the default route name for WebAPI routes, but you can chose any API route name you need. Also notice the presence of the httproute value, which disambiguates WebAPI routes from other MVC routes. You can avoid the httproute parameter if you use the HttpRouteUrl helper method instead:

@Url.HttpRouteUrl("DefaultApi", new { controller="Albumns", id=3 })

An action parameter isn't needed, since API routing uses the HTTP method by default (but you could specify an action in the route parameters, if need be).

Inside an API Controller

An ApiController has a Url helper property with two interesting methods: Link and Route. Link always returns an absolute URL, while Route can produce a relative URL.

The following code uses Link and will produce a URL pointing to the same controller where the code executes:

Url.Link("DefaultApi", new { id = 3 })

If you want a link to a different controller, just pass the controller name along in the route values (along with any other route values the route might support):

Url.Link("DefaultApi", new { controller = "Albums", id = 3})

Note: both the Link and Route methods add an httproute key to the route parameters you pass in. Technically then, you shouldn't use the Url property in an ApiController to generate non-WebAPI links, although it generates the right URL (because regular MVC route handlers don't care about the presence of httproute).

This concludes the extreme excitement of link generation.