简体   繁体   English

为什么使用 CreatedAtAction 在 WebAPI POST 方法中返回 object?

[英]Why return object in WebAPI POST method with CreatedAtAction?

When writing a POST method for an API in Asp.NET Core there is the possibility to use CreatedAtAction在 Asp.NET 内核中为 API 编写 POST 方法时,可以使用CreatedAtAction

Following example from the documentation以下示例来自文档

[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateAsync(Product product)
{
    if (product.Description.Contains("XYZ Widget"))
    {
        return BadRequest();
    }

    await _repository.AddProductAsync(product);

    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}

The CreatedAtAction action result has following effects: CreatedAtAction 动作结果有以下效果:

  1. The Response Status Code will be 201响应状态代码将为 201
  2. A "Location" response Header will be included with the URI of the new resource “位置”响应 Header 将包含在新资源的 URI 中
  3. The created object will be returned in the response body创建的 object 会在响应体中返回

The first two seem reasonable to me.前两个在我看来是合理的。 However I wonder why the third effect would be desired?但是我想知道为什么需要第三种效果? At first it seems to be an unnecessary increase of the response size, yet I am curious to understand why that pattern is presented in the documentation as it is, including the created object.起初,这似乎是响应大小的不必要增加,但我很好奇为什么该模式会按原样出现在文档中,包括创建的 object。 What is the benefit of returning the created resource, which was sent as request anyway?返回作为请求发送的已创建资源有什么好处? Or could it be that the (only) reason for including the object in the response is to include values which are generated server side, as for example a create date or a primary key?或者可能是在响应中包含 object 的(唯一)原因是包含服务器端生成的值,例如创建日期或主键?

The server can generate new data that the client will not know about, such as an ID or timestamps for creation or modification.服务器可以生成客户端不知道的新数据,例如用于创建或修改的 ID 或时间戳。 If the client requires this data after the initial request, you save an unnecessary round trip by including the created resource in the response body.如果客户端在初始请求后需要此数据,您可以通过在响应正文中包含创建的资源来节省不必要的往返行程。

It's not always the best choice.它并不总是最好的选择。 You have weigh the benefit of having immediate access against the increased bandwidth use.您已经权衡了立即访问与增加带宽使用的好处。 Some consideration is warranted before returning large resources this way.在以这种方式返回大量资源之前,需要进行一些考虑。

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

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