CURD (Create, Update, Read, Delete) In ASP.NET Core API

This article gives an overview of create, update, read and delete operations in ASP.Net Core API applications. We will learn from scratch adding new empty API controller Get, Post, Put and Delete data from postman. Here is a  link to download the  postman app. Before this article I strongly recommend that you please read previous article on how to setup an API development environment.
 
Here is the Code,
Step 1
 
Open Visual Studio 2019 and select the ASP.NET Core Web Application template and click Next.
 
 
Name the project ProductServices and click Create.
 
 
In the Create a new ASP.NET Core Web Application dialog, confirm that .NET Core and ASP.NET Core3.1 are selected. Select the API template and click Create.
 
 
Step 2
 
In Solution Explorer, right-click on controllers folder. Select Add >controller. Name the controller ProductsController.
 
 
A window will appear. Choose API Controller-Empty and click "Add".
 
 
After clicking on "Add", another Window will appear with DefaultController. Change the name to ProductsController and click "Add". The ProductsController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Products.
 
 
Marks the class with the [ApiController] attribute. This attribute indicates that the controller responds to web API requests.
 
Uses Dependency Injection to inject the database context (ApplicationDbContext) into the controller. The database context is used in each of the CRUD methods in the controller.
 
Controllers with views include [action] in the route template. API controllers don't include [action] in the route template.
 
Create post method to add new product.
  1. [HttpPost]  
  2.         public async Task<ActionResult<Product>> New(Product product)  
  3.         {  
  4.             db.Products.Add(product);  
  5.             await db.SaveChangesAsync();  
  6.   
  7.             return CreatedAtAction("GetProduct"new { id = product.Id }, product);  
  8.         }  
Step 3
 
Install Postman and Start Postman. Now test post products with postman app. Now build and run your API core application.
  1. Create a new request from postman.
  2. Set the HTTP method to POST from postman dropdowlist.
  3. Now Select the Body tab.
  4. Select the raw radio button.
  5. Set the type to JSON (application/json).
  6. In the request body enter JSON for a products.
  7. Now click on send
 
Step 4
 
Now test GET Method in API.
 
GET/api/product
GET/api/{id}
 
These methods implement two GET endpoints. Test the app by calling the two endpoints from a browser or Postman.
 
http://localhost:49823/api/products
http://localhost:49823/api/products/1
  1. [HttpGet]  
  2.         public async Task<ActionResult<IEnumerable<Product>>> GetProducts()  
  3.         {  
  4.             return await db.Products.ToListAsync();  
  5.         }  
Create GET method to get product by id
  1. [HttpGet("{id}")]  
  2. public async Task<ActionResult<Product>> GetProduct(int id)  
  3. {  
  4.     var product = await db.Products.FindAsync(id);  
  5.   
  6.     if (product == null)  
  7.     {  
  8.         return NotFound();  
  9.     }  
  10.   
  11.     return product;  
  12. }  
  1. Create a new request.
  2. Set the HTTP method to GET.
  3. Set the request URL to https://localhost:<port>/api/Products.
  4. Set two pane view in Postman.
  5. Select Send.
 
Step 5
 
Create Put method to edit existing product. PutProduct or Edit is similar to PostProduct or New, except it uses HTTP PUT. According to the HTTP specification, a PUT request requires the client to send the entire updated entity, not just the changes.
  1. [HttpPut("{id}")]  
  2.         public async Task<IActionResult> Edit(int id, Product product)  
  3.         {  
  4.             if (id != product.Id)  
  5.             {  
  6.                 return BadRequest();  
  7.             }  
  8.   
  9.             db.Entry(product).State = EntityState.Modified;  
  10.   
  11.             try  
  12.             {  
  13.                 await db.SaveChangesAsync();  
  14.             }  
  15.             catch (DbUpdateConcurrencyException)  
  16.             {  
  17.                 if (!ProductExists(id))  
  18.                 {  
  19.                     return NotFound();  
  20.                 }  
  21.                 else  
  22.                 {  
  23.                     throw;  
  24.                 }  
  25.             }  
  26.   
  27.             return NoContent();  
  28.         }  
 
Step 6
 
Create Delete method to delete existing product.
  1. [HttpDelete("{id}")]  
  2.         public async Task<ActionResult<Product>> DeleteProduct(int id)  
  3.         {  
  4.             var product = await db.Products.FindAsync(id);  
  5.             if (product == null)  
  6.             {  
  7.                 return NotFound();  
  8.             }  
  9.   
  10.             db.Products.Remove(product);  
  11.             await db.SaveChangesAsync();  
  12.   
  13.             return product;  
  14.         }  
Test the DeleteProduct method
  1. Use Postman to delete a to-do item:
  2. Set the method to DELETE.
  3. Set the URI of the object to delete (for example https://localhost:5001/api/TodoItems/1).
  4. Select Send.
 
Note
If you find the error "The JSON value could not be converted to System.Int32". Please perform the following steps.
  1. Install Microsoft.AspNetCore.Mvc.NewtonsoftJson which is preview version.
  2. Change to services.AddControllers().AddNewtonsoftJson();