2013-11-27 14 views
30

Ich möchte einen Location header zu meiner HTTP-Antwort hinzufügen, wenn Sie webapi 2 verwenden. Die folgende Methode zeigt, wie Sie dies mithilfe einer benannten Route tun. Weiß jemand, ob Sie den Url.Link mithilfe der Attribut-Routing-Funktion erstellen können, die als Teil von Webapi 2 veröffentlicht wurde?Verwenden von Url.Link mit Attributrouting in Webapi 2

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

Vielen Dank im Voraus

Antwort

48

Sie Route mit Ur.Link verwenden können, wenn Attribut-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

Verwandte Themen