📅  最后修改于: 2023-12-03 14:39:22.210000             🧑  作者: Mango
In ASP.NET Core, the HttpDelete
attribute is used to handle HTTP DELETE requests. By convention, DELETE methods should not have a request body. However, in some cases, you might need to pass data in the request body for a DELETE operation.
In this guide, we will explore how to perform a HttpDelete with a request body in ASP.NET Core.
According to the HTTP specification, the HTTP DELETE method is used to request the server to delete a specified resource. Normally, this method does not include a request body, and the resource to be deleted is identified by the URI (Uniform Resource Identifier) of the HTTP request.
However, there might be scenarios where you need to include additional data in the request body while performing a DELETE operation. This can be achieved by defining a custom model or using a JSON object to pass the data.
To perform an HttpDelete
request with a body, you can follow the steps outlined below:
First, define a model class that represents the data you want to pass in the request body. This model will be used to deserialize the request body into the corresponding object.
public class DeleteModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Next, create a controller method and decorate it with the [HttpDelete]
attribute. Include the [FromBody]
attribute on the parameter to indicate that the data should be retrieved from the request body.
[HttpDelete]
public IActionResult DeleteResource([FromBody] DeleteModel model)
{
// Perform the deletion logic using the model data
// ...
return Ok();
}
Finally, send an HttpDelete
request to the corresponding endpoint, providing the request body in the desired format (e.g., JSON).
DELETE /api/resource-endpoint
Content-Type: application/json
{
"id": 123,
"name": "ResourceName"
}
In this guide, we covered the concept of performing an HttpDelete
request with a body in ASP.NET Core. Although it is recommended to follow HTTP conventions and avoid including a request body in DELETE operations, there might be cases where it becomes necessary to send additional data. By defining a model class, decorating the controller method, and sending the request with the required payload, you can achieve an HttpDelete
request with a body in ASP.NET Core.
Remember to keep the usage of DELETE with a request body to scenarios where the benefits outweigh the deviation from the established conventions.
For more detailed information, refer to the official Microsoft documentation on HttpDeleteAttribute Class.