Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Url.Link with Attribute Routing in Webapi 2

I want to add a Location header to my http response when using webapi 2. The method below shows how to do this using a named route. Does anyone know if you can create the Url.Link using Attribute Routing feature that was released as part of webapi 2?

string uri = Url.Link("DefaultApi", new { id = reponse.Id }); httpResponse.Headers.Location = new Uri(uri); 

Thanks in advance

like image 206
Joel Cunningham Avatar asked Nov 27 '13 04:11

Joel Cunningham


People also ask

Which types of routing is supported in Web API 2?

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.

How do I specify a route in Web API?

The default route template for Web API is "api/{controller}/{id}". In this template, "api" is a literal path segment, and {controller} and {id} are placeholder variables. When the Web API framework receives an HTTP request, it tries to match the URI against one of the route templates in the routing table.

Why API segment is used in Web API routing?

The reason for using “api” in the route is to avoid collisions between the ASP.NET Web API and MVC routing. So, you can have “/products” go to the MVC controller, and “/api/products” go to the Web API controller.


1 Answers

You can use RouteName with Ur.Link when using attribute routing.

public class BooksController : ApiController {     [Route("api/books/{id}", Name="GetBookById")]     public BookDto GetBook(int id)      {         // Implementation not shown...     }      [Route("api/books")]     public HttpResponseMessage Post(Book book)     {         // Validate and add book to database (not shown)          var response = Request.CreateResponse(HttpStatusCode.Created);          // Generate a link to the new book and set the Location header in the response.         string uri = Url.Link("GetBookById", new { id = book.BookId });         response.Headers.Location = new Uri(uri);         return response;     } } 

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names

like image 91
Joel Cunningham Avatar answered Oct 10 '22 11:10

Joel Cunningham