简体   繁体   English

.NET Web API HttpResponseMessage模式?

[英].NET Web API HttpResponseMessage Pattern?

So I've seen the Web API 2 Controllers return HttpResponse and the actual object. 所以我看到Web API 2控制器返回HttpResponse和实际对象。 Example: 例:

 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)
        };
    }

or 要么

 public Application Get(string id)
    {
        return apps.Single(c => c.Id == id);
    }

My question which is the 'right' way? 我的问题是“正确”的方式? #2 is much shorter but is it better to do #1 or does #2 do #1 automatically ... ? #2要短得多但是#1更好或#2自动做#1#?

See this and this SO questions. 看到这个这个问题。

The response will be the same ( HttpResponseMessage ) in both cases. 两种情况下的响应都是相同的( HttpResponseMessage )。

HttpResponseMessage allows you to work with HTTP protocol (eg, via Headers property) and unifies your return type. HttpResponseMessage允许您使用HTTP协议(例如,通过Headers属性)并统一您的返回类型。

Returning CLR types can be more readable, but you loose flexibility to return different types with different status codes unless you use dynamic or object which defeats the purpose of returning a specific type. 返回CLR类型可以更具可读性,但是您可以放松使用不同状态代码返回不同类型的灵活性,除非您使用dynamicobject来抵消返回特定类型的目的。

Personally, I prefer to use IHttpActionResult (added in v2) and to specify a ResponseTypeAttribute on controller actions for the expected return type to improve readability. 就个人而言,我更喜欢使用IHttpActionResult (在v2中添加)并在控制器操作上为预期的返回类型指定ResponseTypeAttribute以提高可读性。

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

    return Ok(portfolio);
}

You can easily manipulate response messages (in a RESTful way) using default IHttpActionResult implementations (see OkResult above). 您可以使用默认的IHttpActionResult实现轻松地操作响应消息(以RESTful方式)(请参阅上面的OkResult )。 Avoiding constructing HttpResponseMessage yourself also keeps code clean. 避免自己构造HttpResponseMessage也可以保持代码清洁。 Here is an official article on IHttpActionResult and here is an interesting SO conversation on HttpResponseMessage vs IHttpActionResult . 是关于IHttpActionResult的官方文章, 是关于HttpResponseMessageIHttpActionResult一个有趣的SO对话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM