Building Web API With ASP.NET Core MVC And Visual Studio Code

Introduction

ASP.NET Core has built-in support for building Web API, using MVC framework. This framework is able to work with both UI (HTML) and Web API's as they share the same code base and pipelines.

What’s exactly changed compared to the previous version?

Previously, we had to use different libraries to create MVC Controller and Web API Controller. Now, in ASP.NET Core, both are combined together.

As Web API and MVC are used with the same code base, it does not require to create different action filters. This means that we can use same action filter for both the Application frameworks, MVC and Web API.

The way of defining attribute routing is extended. We can use "[Route("api/[controller]")]" as attribute routing on top of Controller. It means, every action of this Controller will be accessed, using route "api/controller name". Here, we do not require to write the Controller name. Only "[controller]"will work for us.

  1. [Route("api/[controller]")]  
  2. public class HomeController : Controller  
  3. {  
  4.   
  5. }  
In my previous article, “Build Your First ASP.NET MVC Core Application with Visual Studio Code”, I have explained how to create MVC Application, using .NET Core framework. In same way, we can create Web API project.

Implement CRUD operations

To test the Application, I am using Telerik's Fiddler. It’s free. Using Fiddler, we can analyze the input/ output of URL and also POST the data without any user interface.

In the section given below, I have performed CRUD operation on the static data by using the code given below.

  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3.   
  4. namespace WebApplication  
  5. {  
  6.     [Route("api/[controller]")]  
  7.     public class HomeController : Controller  
  8.     {  
  9.         static List<TestModel> staticData;  
  10.         public HomeController()   
  11.         {  
  12.             staticData = GetData();  
  13.         }  
  14.         private List<TestModel> GetData()  
  15.         {  
  16.             List<TestModel> data = new List<TestModel>();  
  17.             data.Add(new TestModel { Id = 1, Name = "Jignesh Trivedi" });  
  18.             data.Add(new TestModel { Id = 2, Name = "Tejas Trivedi" });  
  19.             data.Add(new TestModel { Id = 3, Name = "Rakesh Trivedi" });  
  20.             data.Add(new TestModel { Id = 4, Name = "Aakash Patel" });  
  21.   
  22.             return data;  
  23.         }  
  24.     }  
  25. }  
Create Operation (CRUD) 

POST verb is used for adding an item to the data source. It generally accepts the data from the client and posts the data over HTTP in the request body.

To catch the POST request, I am using the code given below. 

  1. [HttpPost]  
  2.     public IActionResult Create([FromBody] TestModel item)  
  3.     {  
  4.         if (item == null)  
  5.         {  
  6.             return BadRequest();  
  7.         }  
  8.         //Add new item   
  9.         staticData.Add(item);  
  10.         return CreatedAtRoute("GetById"new { id = item.Id }, item);  
  11.     }  
The [FromBody] attribute tells MVC to get the value of the model from the HTTP request body.

Output


The “Create” method will return Http Status code 201 i.e. standard response for an HTTP POST method that creates a new resource on the Server.

Read Operation (CRUD)

GET verb is also being used to retrieve a specific item; we just require additional information such as key in the URL. The code given below can be used to retrieve a specific item.

Here, I have added two GET methods, one for retrieving all the records and a second one to retrieve the specific records.

  1. [HttpGet("")]  
  2. public IEnumerable<TestModel> GetAll()  
  3. {  
  4.     return staticData;  
  5. }  
  6.   
  7. [HttpGet("{id}", Name = "GetById")]  
  8. public IActionResult GetById(int id)  
  9. {  
  10.     var item = staticData.Find(d=> d.Id == id);  
  11.     if (item == null)  
  12.     {  
  13.         return NotFound();  
  14.     }  
  15.     return new ObjectResult(item);  
  16. }  
“GetAll” returns all the records. MVC automatically serializes the return object to JSON and writes JSON into body of the response message.


In the second method, HttpGet attribute has "{id}" placeholder variable for Id of the Model item. When the method "GetById" is invoked, it assigns the value of "{id}" in the URL to the method's Id parameter.


System returns "404 – Not found" error when Id is not found in static data.


Update Operation (CRUD)

PATCH or PUT verbs are used for update operation. The main difference between PATCH and PUT is that PATCH is used to perform partial update and PUT replaces the entire entity with the new received object.

  1. [HttpPut("{id}")]  
  2. public IActionResult Update(int id, [FromBody] TestModel item)  
  3. {  
  4.     if (item == null || item.Id != id)  
  5.     {  
  6.         return BadRequest();  
  7.     }  
  8.     var updateItem = staticData.Find(d=> d.Id == id);  
  9.     if (updateItem == null)  
  10.     {  
  11.         return NotFound();  
  12.     }  
  13.     //Update Item  
  14.     return new NoContentResult();  
  15. }  
System returns "201 – No Content" when transaction is successful.

Output


Delete Operation (CRUD)

The Delete method is very straightforward. This method just accepts a key and based on the key, we need to write the logic to remove an entity.

  1. [HttpDelete("{id}")]  
  2. public IActionResult Delete(int id)  
  3. {  
  4.     var modelItem = staticData.Find(d=> d.Id == id);  
  5.     if (modelItem == null)  
  6.     {  
  7.         return NotFound();  
  8.     }  
  9.   
  10.     //Remove Item  
  11.     return new NoContentResult();  
  12. }  
The system returns the same response as Update.

Output


Summary

In ASP.NET Core, code for Web API and MVC is merged and now, both use the same code base and pipelines. Using the methods described in this article, we can create Web API, using .NET Core framework.