2013-11-27 13 views
30

webapi 2を使用しているときに、http応答にLocationヘッダーを追加したいとします。以下のメソッドは、名前付きルートを使用してこれを行う方法を示しています。 webapi 2の一部としてリリースされた属性ルーティング機能を使用してUrl.Linkを作成できるかどうかを知っていますか?属性ルーティングを使用するときは、Ur.LinkでRouteNameを使用することができ、事前Webapi 2の属性ルーティングでUrl.Linkを使用する

答えて

48

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

感謝。

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

関連する問題