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 });
1

1 Answer 1

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 } );
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, this was the solution I needed. Thanks!
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 =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.