Building RESTful Web Services with .NET Core
上QQ阅读APP看书,第一时间看更新

DELETE

Ideally, a DELETE request should delete the resource. Once the operation is successful, we can send a 200 OK status code by calling the OK() method.

Refer to the following code block:

// DELETE: api/Products/1
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
=> (await _productService.DeleteOrderAsync(id))
? (IActionResult)Ok()
: NoContent();

Notice the DeleteOrderAsync method, which is provided with the ID of the product to delete. Now, you can return a Boolean from that method, which will indicate whether the operation was successful or not. If you don't find any product for that ID, simply return false.  Then, we will decide what to return to the client accordingly.

If you return falseNoContent() can be used to return status code 204. If the resource is already deleted and the client is requesting the same, then the server will return a status code 204 No Content. That means the server is not able to find the requested resource as it does not exist anymore.

Have a look at the Postman screenshot. See the Status code is 200 OK for a successful delete: