Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for Url.Link when using attribute routing

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 });
like image 327
ainteger Avatar asked Nov 20 '13 08:11

ainteger


People also ask

What is attribute-based routing in Web API?

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. For example, you can easily create URIs that describe hierarchies of resources.

What is difference between attribute and conventional routing?

Conventional routing: The route is determined based on conventions that are defined in route templates that, at runtime, will map requests to controllers and actions (methods). Attribute-based routing: The route is determined based on attributes that you set on your controllers and methods.

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.


1 Answers

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 } );
like image 108
Kiran Avatar answered Oct 06 '22 19:10

Kiran