Back to: ASP.NET Core Web API Tutorials
HTTP DELETE Method in ASP.NET Core Web API
In this article, I will discuss How to Implement the HTTP DELETE Method in ASP.NET Core Web API Application with Real-Time Examples. Please read our previous article discussing the HTTP PATCH Method in ASP.NET Core Web API with Examples.
HTTP DELETE Method in ASP.NET Core Web API
The HTTP DELETE method is used in ASP.NET Core Web API to delete resources identified by a URI. Implementing a DELETE endpoint in ASP.NET Core Web API provides a way for clients to remove resources from the server.
DELETE requests are considered idempotent, meaning that multiple identical DELETE requests should have the same effect as a single request. This property is essential for the reliability and predictability of Web APIs. Using DELETE in ASP.NET Core Web API ensures that clients can safely repeat the same request without causing unintended effects, assuming the resource exists and is deletable.
Return the correct HTTP status codes to indicate the outcome of the DELETE request. Commonly used status codes include 204 No Content on successful deletion, 404 Not Found if the resource does not exist, and 403 Forbidden or 401 Unauthorized if the request lacks proper authorization.
How Do We Implement HTTP DELETE Method in ASP.NET Core Web API?
When you design a Web API for managing resources like users, products, or other entities, implementing the DELETE method allows clients to request the deletion of a resource. In ASP.NET Core Web API, we can implement the DELETE End Point using HttpDelete Attribute by decorating it with the action method. Let us proceed and understand this with an example.
Define Product Model
Create a Product class inside the Models folder. This class will represent the product entity. Once you create the Product.cs class file, copy and paste the following code:
namespace HTTPMethodDemo.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public int Price { get; set; } public int Quantity { get; set; } public string? Description { get; set; } } }
Create Product Service
Create a class file named ProductRepository.cs, and copy and paste the following code. This is the repository where we will perform all database operations related to the Product model. As you can see, we have implemented two methods. The GetById method will retrieve the Product details based on the Product ID, while the DeleteProduct method deletes a Product from the database.
namespace HTTPMethodDemo.Models { public class ProductRepository { public List<Product> Products = new List<Product>() { new Product() { Id = 1, Name= "Laptop", Price = 1000, Quantity = 10, Description = "A high-performance Laptop." }, new Product() { Id = 2, Name= "Desktop", Price = 2000, Quantity = 20 } //Description is Optional }; public Product GetById(int Id) { // Find a product by ID return Products.FirstOrDefault(p => p.Id == Id); } public void DeleteProduct(Product product) { Products.Remove(product); } } }
Register Product Repository Service:
Please add the following statement to the Program.cs class file. This will add the service to the dependency injection container so that we can inject it into the controller and use the service implementations.
builder.Services.AddScoped<ProductRepository>();
Creating Product Controller:
Create an Empty API Controller within the Controllers folder named ProductController and then copy and paste the following code. This Product Controller will contain the action method that handles DELETE HTTP requests.
using HTTPMethodDemo.Models; using Microsoft.AspNetCore.Mvc; namespace HTTPMethodDemo.Controllers { [Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { private readonly ProductRepository _productRepository; public ProductController(ProductRepository productRepository) { _productRepository = productRepository; } // DELETE: api/Product/1 [HttpDelete("{Id}")] public IActionResult DeleteProduct(int Id) { var product = _productRepository.GetById(Id); if (product == null) { return NotFound(); } _productRepository.DeleteProduct(product); // Returns a 204 No Content response return NoContent(); } } }
Testing the API End Point:
Now, run the application and test the API endpoint, and it should work as expected:
API: DELETE an Existing Product
URL: https://localhost:7047/api/Product/1
Method: DELETE
Response:
Implementing Asynchronous HTTP DELETE Method in ASP.NET Core Web API:
In most real-time applications, we must make the action methods or services async if they perform I/O operations. Let us see how we can implement this.
Modifying the ProductRepository:
First, modify the ProductRepository.cs class file as follows. Here, we are making both the GetById and DeleteProduct methods async. We are delaying the execution of the action method by 1 second using the await keyword. Let’s assume this is the time period that the server will take to communicate with the database and perform the operation. Also, we changed the method name by appending the word Async.
namespace HTTPMethodDemo.Models { public class ProductRepository { public List<Product> Products = new List<Product>() { new Product() { Id = 1, Name= "Laptop", Price = 1000, Quantity = 10, Description = "A high-performance Laptop." }, new Product() { Id = 2, Name= "Desktop", Price = 2000, Quantity = 20 } //Description is Optional }; public async Task<Product> GetByIdAsync(int Id) { await Task.Delay(TimeSpan.FromSeconds(1)); // Find a product by ID return Products.FirstOrDefault(p => p.Id == Id); } public async Task DeleteProductAsync(Product product) { await Task.Delay(TimeSpan.FromSeconds(1)); Products.Remove(product); } } }
Modifying the Product Controller:
Next, modify the ProductController to make the action method Asynchronous. Also, while calling the ProductRepository services, we are using the await keyword so that the Main Thread will not be blocked.
using HTTPMethodDemo.Models; using Microsoft.AspNetCore.Mvc; namespace HTTPMethodDemo.Controllers { [Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { private readonly ProductRepository _productRepository; public ProductController(ProductRepository productRepository) { _productRepository = productRepository; } // DELETE: api/Product/1 [HttpDelete("{Id}")] public async Task<IActionResult> DeleteProduct(int Id) { var product = await _productRepository.GetByIdAsync(Id); if (product == null) { return NotFound(); } await _productRepository.DeleteProductAsync(product); // Returns a 204 No Content response return NoContent(); } } }
With the above changes in place, run the application and test the endpoint by issuing an HTTP DELETE Request. It should work as expected.
When Should We Use HTTP DELETE Method in ASP.NET Core Web API?
The HTTP DELETE method is used in ASP.NET Core Web APIs to remove resources from a server. Here is when you should consider using the DELETE method in your ASP.NET Core Web API:
- Removing Resources: The primary use case for the HTTP DELETE method is to delete a resource identified by a URI. When a client sends a DELETE request to a server, it asks the server to remove the specified resource. In the context of an ASP.NET Core Web API, this typically involves removing an entity from a database, such as a user profile, a blog post, or any other data entity the API manages.
When Not to Use:
- Not for Updates: DELETE is specifically for removal. If you’re modifying or updating a resource, PUT or PATCH methods are more appropriate.
- Not for Non-Deletable Resources: If the operation should not allow the resource to be permanently removed (e.g., archiving or deactivating for audit purposes), consider using a different method to change the state of the resource without actual deletion.
Best Practices to Use HTTP DELETE Method:
- Permission and Validation Checks: Before executing a DELETE operation, your ASP.NET Core Web API should perform necessary permission checks and validations to ensure that the request is authorized and the operation is valid. This might involve checking if the user has the right to delete the resource or if the resource is in a state that allows deletion.
- Confirmation Before Deletion: Depending on the client application, you might want to implement a confirmation step before performing a DELETE operation to prevent accidental deletions.
- Secure DELETE Endpoints: Implement security measures such as authentication and authorization to ensure only authorized users can perform DELETE operations.
- Cascading Deletes and Side Effects: In some cases, deleting a resource might involve cascading deletes or other side effects. For instance, deleting a user account might also involve deleting posts, comments, or other related data owned by the user. When implementing DELETE operations, carefully consider and document these behaviors to ensure the API behaves as expected.
- Feedback to the Client: Provide clear and actionable feedback through HTTP status codes and messages when a request cannot be processed.
- Logging: Add logging to track delete operations, which can help debugging and auditing.
In the next article, I will discuss How to Implement the HTTP HEAD Method in ASP.NET Core Web API Application with Examples. In this article, I explain How to Implement the HTTP DELETE Method in ASP.NET Core Web API with Examples. I hope you enjoy this article, ” HTTP DELETE Method in ASP.NET Core Web API.”