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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Route("api/user/{id}")] | |
public virtual HttpResponseMessage Post(User user) | |
{ | |
if (!ModelState.IsValid) | |
{ | |
return Request.CreateResponse(HttpStatusCode.BadRequest); | |
} | |
Session.SaveOrUpdate(user); | |
var response = Request.CreateResponse(HttpStatusCode.Created, user); | |
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.Id })); //We are using the route name from the route table here | |
return response; | |
} | |
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 }));