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 });
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.
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.
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.
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 } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With