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.
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.
- [HttpPost]
- public async Task<ActionResult<Product>> New(Product product)
- {
- db.Products.Add(product);
- await db.SaveChangesAsync();
-
- return CreatedAtAction("GetProduct", new { id = product.Id }, product);
- }
Step 3
Install Postman and Start Postman. Now test post products with postman app. Now build and run your API core application.
- Create a new request from postman.
- Set the HTTP method to POST from postman dropdowlist.
- Now Select the Body tab.
- Select the raw radio button.
- Set the type to JSON (application/json).
- In the request body enter JSON for a products.
- 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
- [HttpGet]
- public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
- {
- return await db.Products.ToListAsync();
- }
Create GET method to get product by id
- [HttpGet("{id}")]
- public async Task<ActionResult<Product>> GetProduct(int id)
- {
- var product = await db.Products.FindAsync(id);
-
- if (product == null)
- {
- return NotFound();
- }
-
- return product;
- }
- Create a new request.
- Set the HTTP method to GET.
- Set the request URL to https://localhost:<port>/api/Products.
- Set two pane view in Postman.
- 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.
- [HttpPut("{id}")]
- public async Task<IActionResult> Edit(int id, Product product)
- {
- if (id != product.Id)
- {
- return BadRequest();
- }
-
- db.Entry(product).State = EntityState.Modified;
-
- try
- {
- await db.SaveChangesAsync();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!ProductExists(id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
-
- return NoContent();
- }
Step 6
Create Delete method to delete existing product.
- [HttpDelete("{id}")]
- public async Task<ActionResult<Product>> DeleteProduct(int id)
- {
- var product = await db.Products.FindAsync(id);
- if (product == null)
- {
- return NotFound();
- }
-
- db.Products.Remove(product);
- await db.SaveChangesAsync();
-
- return product;
- }
Test the DeleteProduct method
- Use Postman to delete a to-do item:
- Set the method to DELETE.
- Set the URI of the object to delete (for example https://localhost:5001/api/TodoItems/1).
- Select Send.
Note
If you find the error "The JSON value could not be converted to System.Int32". Please perform the following steps.
- Install Microsoft.AspNetCore.Mvc.NewtonsoftJson which is preview version.
- Change to services.AddControllers().AddNewtonsoftJson();