17

I have upgraded my project from webapi to webapi2 and are now using attribute routing. I had a method where I used Url helper to get url. Which is the best way to replace Url helper (because this is not working for attributes).

My example code of old usage:

protected Uri GetLocationUri(object route, string routeName = WebApiConfig.RouteDefaultApi)
{
    string uri = Url.Link(routeName, route);
    return new Uri(uri);
}

Config of routes:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: RouteDefaultApi,
        routeTemplate: "{controller}/{id}/{action}",
        defaults: new { id = RouteParameter.Optional, action = "Default" }
    );           
}

Usage:

Uri myUrl = GetLocationUri(route: new { action = "images", id = eventId });
abatishchev
  • 98,240
  • 88
  • 296
  • 433
ainteger
  • 518
  • 4
  • 21

1 Answers1

41

Why are you trying to use the conventional route RouteDefaultApi when you want to generate links to an attributed route of a controller/action ?

Following is an example usage of how you need to use Url.Link with attribute routing:

[Route("api/values/{id}", Name = "GetValueById")]
public string GetSingle(int id)

Url.Link("GetValueById", new { id = 10 } );
Kiran
  • 56,921
  • 15
  • 176
  • 161
  • Perfect, this was the solution I needed. Thanks! – ainteger Nov 21 '13 at 07:06
  • 1
    Superb! I used a class constant - `private const string GET_VALUE_BY_ID = "GetValueById";` - and plugged that into the attribute and argument so the two stay connected if at one point some decides to rename it =) – Nebula Aug 21 '15 at 09:35