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.
- [Route("api/[controller]")]
- public class HomeController : Controller
- {
-
- }
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.
- using System.Collections.Generic;
- using Microsoft.AspNetCore.Mvc;
-
- namespace WebApplication
- {
- [Route("api/[controller]")]
- public class HomeController : Controller
- {
- static List<TestModel> staticData;
- public HomeController()
- {
- staticData = GetData();
- }
- private List<TestModel> GetData()
- {
- List<TestModel> data = new List<TestModel>();
- data.Add(new TestModel { Id = 1, Name = "Jignesh Trivedi" });
- data.Add(new TestModel { Id = 2, Name = "Tejas Trivedi" });
- data.Add(new TestModel { Id = 3, Name = "Rakesh Trivedi" });
- data.Add(new TestModel { Id = 4, Name = "Aakash Patel" });
-
- return data;
- }
- }
- }
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.
- [HttpPost]
- public IActionResult Create([FromBody] TestModel item)
- {
- if (item == null)
- {
- return BadRequest();
- }
-
- staticData.Add(item);
- return CreatedAtRoute("GetById", new { id = item.Id }, item);
- }
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.
- [HttpGet("")]
- public IEnumerable<TestModel> GetAll()
- {
- return staticData;
- }
-
- [HttpGet("{id}", Name = "GetById")]
- public IActionResult GetById(int id)
- {
- var item = staticData.Find(d=> d.Id == id);
- if (item == null)
- {
- return NotFound();
- }
- return new ObjectResult(item);
- }
“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.
- [HttpPut("{id}")]
- public IActionResult Update(int id, [FromBody] TestModel item)
- {
- if (item == null || item.Id != id)
- {
- return BadRequest();
- }
- var updateItem = staticData.Find(d=> d.Id == id);
- if (updateItem == null)
- {
- return NotFound();
- }
-
- return new NoContentResult();
- }
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.
- [HttpDelete("{id}")]
- public IActionResult Delete(int id)
- {
- var modelItem = staticData.Find(d=> d.Id == id);
- if (modelItem == null)
- {
- return NotFound();
- }
-
-
- return new NoContentResult();
- }
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.