简体   繁体   中英

Web API 2 which is the best way to return empty body for 201 responses

In Web API 2 POST method it seems that the best way to respond is using the CreatedAtRoute method. However in certain responses I would like that the body of the response is empty. Thus only replying with 201 and a location header.

I would expect this to work:

[HttpPost]
[ResponseType(typeof(Product))]
public IHttpActionResult Post([FromBody] Product product)
{
    products.Add(product);
    return CreatedAtRoute<Product>("", new {id = product.Id}, null);
}

However inspecting this in Postman, it actually returns a string "null". Is there an elegant way to do this?

You can use the built in "Created" method for simplicity but you've said that the response type should be a "Product".

Created("getPathHere", newProductObject);

Otherwise, remove the response type of Product, return the new product id instead (and any status that this creation process is in if it isn't instantaneous).

Created(string.Format("/api/Products/{0}", productId), new { ProductId = productId, Status = "Awaiting Manufacture" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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