2014-08-28 35 views
1

我有以下Api Controller的ASP.NET Web API設置自定義狀態代碼

[HttpPost] 
public User Create(User user) 
{ 
    User user = _domain.CreateUser(user); 
    //set location header to /api/users/{id} 
    //set status code to 201 
    //return the created user 
} 

好像我們不得不依靠Request.CreateResponse(..)和更改控制器的簽名,以返回IHttpActionResult

我不想更改方法簽名,因爲它對於文檔目的非常有用。我能夠使用HttpContext.Current.Response...添加Location標題,但無法設置狀態碼。

有人對此有更好的想法嗎?

回答

1

因爲您在void,HttpResponseMessage和IHttpActionResult之外使用自定義(其他)返回類型 - 指定狀態代碼更困難。見Action Results in Web API 2

Exception Handling in Web API.如果你想堅持不修改返回類型,那麼這可能是一些你可以做的設置狀態代碼:

[HttpPost] 
public User Create(User user) 
{ 
    User user = _domain.CreateUser(user); 
    //set location header to /api/users/{id} 

    //set status code to 201 
    if (user != null) 
    { 
     //return the created user 
     throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Created, user); 
    } 
    else 
    { 
     throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError));   
    } 
} 
+1

這不是一個很好的答案。它不應該得到一個downvote,因爲它的確如它所說的那樣,但拋出異常來獲得期望的行爲在這裏是很方便的。 – 2015-11-13 08:32:23

+0

使用例外來表示正常結果不是合理的答案。 – 2016-08-25 03:19:33

+0

從這兩篇文章中,www.asp.net推薦的方法是設置特定的狀態碼並返回一個自定義對象。 – Nhan 2017-10-05 00:47:37