簡體   English   中英

.NET Web API HttpResponseMessage模式?

[英].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類型可以更具可讀性,但是您可以放松使用不同狀態代碼返回不同類型的靈活性,除非您使用dynamicobject來抵消返回特定類型的目的。

就個人而言,我更喜歡使用IHttpActionResult (在v2中添加)並在控制器操作上為預期的返回類型指定ResponseTypeAttribute以提高可讀性。

[HttpGet]
[ResponseType(typeof(Portfolio))]
public IHttpActionResult GetPortfolio([FromUri] long id)
{
    // get portfolio

    return Ok(portfolio);
}

您可以使用默認的IHttpActionResult實現輕松地操作響應消息(以RESTful方式)(請參閱上面的OkResult )。 避免自己構造HttpResponseMessage也可以保持代碼清潔。 是關於IHttpActionResult的官方文章, 是關於HttpResponseMessageIHttpActionResult一個有趣的SO對話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM