[英].NET Web API HttpResponseMessage Pattern?
所以我看到Web API 2控制器返回HttpResponse
和實際對象。 例:
public HttpResponseMessage Get(string id)
{
var app = apps.Single(c => c.Id == id);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(app,
Configuration.Formatters.JsonFormatter)
};
}
要么
public Application Get(string id)
{
return apps.Single(c => c.Id == id);
}
我的問題是“正確”的方式? #2要短得多但是#1更好或#2自動做#1#?
兩種情況下的響應都是相同的( HttpResponseMessage
)。
HttpResponseMessage
允許您使用HTTP協議(例如,通過Headers
屬性)並統一您的返回類型。
返回CLR類型可以更具可讀性,但是您可以放松使用不同狀態代碼返回不同類型的靈活性,除非您使用dynamic
或object
來抵消返回特定類型的目的。
就個人而言,我更喜歡使用IHttpActionResult
(在v2中添加)並在控制器操作上為預期的返回類型指定ResponseTypeAttribute
以提高可讀性。
[HttpGet]
[ResponseType(typeof(Portfolio))]
public IHttpActionResult GetPortfolio([FromUri] long id)
{
// get portfolio
return Ok(portfolio);
}
您可以使用默認的IHttpActionResult
實現輕松地操作響應消息(以RESTful方式)(請參閱上面的OkResult
)。 避免自己構造HttpResponseMessage
也可以保持代碼清潔。 這是關於IHttpActionResult
的官方文章, 這是關於HttpResponseMessage
和IHttpActionResult
一個有趣的SO對話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.