Thursday, March 6, 2014

ASP.NET Web API 2: Attribute routing and Url.Link()

After upgrading to ASP.NET Web API 2, we decided to switch to the attribute based routing approach. Most things worked nicely, but we had one little problem.

In our POST methods, we returned the URL of the new created object:

The problem was that Url.Link expects a route name, but how do we specify the correct route name? Therefore an extra “Name” property is available on the Route attribute:

[Route("api/user/{id}", Name = "PostUser")]

response.Headers.Location = new Uri(Url.Link("PostUser", new { id = user.Id }));