Monday, June 16, 2014

ASP.NET Web API: Combining Attribute Based Routing and Url.Link

Similar to ASP.NET MVC, ASP.NET Web API offers the Url.Link method which allows you to generate a url based on the configured route information.

The thing is that if you look at the method signature the Link method expects a routeName:

public virtual string Link( string routeName, Object routeValues )

This works perfect when you are using the default code based routing configuration:

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

But when you are using the ASP.NET Web API Attribute based routing, you don’t have a route name!? So how can we still use the Url.Link method?

The ASP.NET team was smart enough to think about this scenario and they provided an extra property on the Route attribute called Name:

No comments: