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
標題,但無法設置狀態碼。
有人對此有更好的想法嗎?
這不是一個很好的答案。它不應該得到一個downvote,因爲它的確如它所說的那樣,但拋出異常來獲得期望的行爲在這裏是很方便的。 – 2015-11-13 08:32:23
使用例外來表示正常結果不是合理的答案。 – 2016-08-25 03:19:33
從這兩篇文章中,www.asp.net推薦的方法是設置特定的狀態碼並返回一個自定義對象。 – Nhan 2017-10-05 00:47:37