.NET的Web API的Htt presponseMessage模式?模式、Web、NET、API

2023-09-03 16:40:25 作者:知足 Content つ

所以,我在网上看到API 2控制器返回的Htt presponse 和实际的对象。例如:

So I've seen the Web API 2 Controllers return HttpResponse and the actual object. 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)
        };
    }

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

我的问题是正确的方式? #2要短得多,但它不如做1号还是2号自动完成#1 ...?

My question which is the 'right' way? #2 is much shorter but is it better to do #1 or does #2 do #1 automatically ... ?

推荐答案

请参阅this和this SO问题。

See this and this SO questions.

的反应将是相同的(Htt的presponseMessage )在这两种情况下。

The response will be the same (HttpResponseMessage) in both cases.

的Htt presponseMessage 允许您使用HTTP协议的工作(例如,通过标题属性),并统一您的返回类型。

HttpResponseMessage allows you to work with HTTP protocol (e.g., via Headers property) and unifies your return type.

返回CLR类型可以是更具可读性,但除非你用宽松的灵活性,以返回不同类型具有不同的地位codeS 动态对象这违背返回一个特定类型的目的。

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.

我个人preFER使用 IHttpActionResult (v2中添加的),并指定一个 ResponseTypeAttribute 上对于预期收益型控制器的操作,以提高可读性。

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.

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

    return Ok(portfolio);
}

您可以使用易于操作的响应消息(REST方式)默认 IHttpActionResult 实现(见 OkResult 以上) 。避免建设的Htt presponseMessage 自己也保留code干净。 这里是一个在 IHttpActionResult 官方的文章和here是一个有趣的SO对话在的Htt presponseMessage VS IHttpActionResult

You can easily manipulate response messages (in a RESTful way) using default IHttpActionResult implementations (see OkResult above). Avoiding constructing HttpResponseMessage yourself also keeps code clean. Here is an official article on IHttpActionResult and here is an interesting SO conversation on HttpResponseMessage vs IHttpActionResult.