Question

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 });
Was it helpful?

Solution

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 } );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top