Quick Start To Create RESTful Web API In ASP.NET Core

As ASP.NET MVC and Web APIs are almost the same, Microsoft combined them both in ASP.NET Core platform and made it more featured and powerful. Earlier, we discussed how to quickly configure MVC in ASP.NET Core from scratch and view injection using inject in ASP.NET Core MVC. Those articles were more focused on ASP.NET Core MVC. In this post, we will create simple web API (REST) and test it from browser.

Let's begin.

In Visual Studio, create a new project (File > New > Project), and select ASP.NET Core Web Application (.NET Core).

Project

Assign a name to the application CoreWebAPI and click OK.

In dialog, select Web API template and click OK. This will generate default ASP.NET Core Web API project.

 WEB API
 
Let's see what has been changed in project.json file. As ASP.NET Core provides a common platform for MVC and Web API, it will include Microsoft.AspNetCore.Mvc instead of its own web API dependencies.

Once we create a web API project, it will generate default ValuesController which has default Get, Put, Post, and Delete actions. We will ignore it and create our own API Controller.

The setup is over. Let's create new API to expose the data from API call.

Add a Controller class

In Solution Explorer, right click on Controllers folder, Add > New Item. Select web API controller class. Enter the controller name ProductController and tap Add.
 
add
 
Visual studio scaffold's default actions whenever we create a new web API Controller Class. 
  1. [Route("api/[controller]")]  
  2. public class ProductController : Controller  
  3. {  
  4.     // GET: api/values  
  5.     [HttpGet]  
  6.     public IEnumerable<string> Get()  
  7.     {  
  8.         return new string[] { "value1""value2" };  
  9.     }  
  10.   
  11.     // GET api/values/5  
  12.     [HttpGet("{id}")]  
  13.     public string Get(int id)  
  14.     {  
  15.         return "value";  
  16.     }  
  17.   
  18.     // POST api/values  
  19.     [HttpPost]  
  20.     public void Post([FromBody]string value)  
  21.     {  
  22.     }  
  23.   
  24.     // PUT api/values/5  
  25.     [HttpPut("{id}")]  
  26.     public void Put(int id, [FromBody]string value)  
  27.     {  
  28.     }  
  29.   
  30.     // DELETE api/values/5  
  31.     [HttpDelete("{id}")]  
  32.     public void Delete(int id)  
  33.     {  
  34.     }  
  35. }   
If you have observed, API Controller is inheriting Controller base class instead of ApiController. ASP.NET Core makes it happen.

Add a model class

Add a new folder in the project and name it "Models". Now, right click on the Models folder and Add > Class. Name the class Product and click Add.
  1. public class Product  
  2. {  
  3.     public int ProductId { getset; }  
  4.     public string Name { getset; }  
  5.     public decimal Price { getset; }  
  6.     public DateTime CreatedDate { getset; }  
  7. }  

Add a Service class

In Solution Explorer, right click on the Models folder and Add >Class. Name the class ProductService and tap Add. ProductService class has method GetProducts that returns a list of products. 
  1. public static List<Product> GetProducts()  
  2. {  
  3.     return new List<Product>()  
  4.     {  
  5.         new Product {ProductId=1, Name="Product 1",Price=100,CreatedDate=DateTime.Now },  
  6.         new Product {ProductId=2, Name="Product 2",Price=200,CreatedDate=DateTime.Now },  
  7.         new Product {ProductId=3, Name="Product 3",Price=300,CreatedDate=DateTime.Now },  
  8.         new Product {ProductId=4, Name="Product 4",Price=400,CreatedDate=DateTime.Now },  
  9.         new Product {ProductId=5, Name="Product 5",Price=500,CreatedDate=DateTime.Now },  
  10.     };  
  11. }  

Routing

ASP.NET Core introduces new attribute-based routing tokens, such as [controller] and [action]. These tokens are replaced at the run time with the name of the controller or action, respectively, to which the attribute has been applied. This reduces the hard coded route attribute parameters in Controllers. 
  1. [Route("api/[controller]")]   
[controller] will automatically be replaced with the controller name at run time.

Attribute-based routing has also been introduced with the various [Http{Verb}] attributes. So, you can succinctly state that a GET request with an ‘id’ will be handled by the Get method.
  1. [HttpGet("{id}")]  
  2. public string Get(int id)  
  3. {  
  4.     return "value";  
  5. }  
To return a list of products from Web API controller, replace Get() action with the below code. ProductService.GetProducts() will return the list of products.
  1. [HttpGet]  
  2. public List<Product> Get()  
  3. {  
  4.     return ProductService.GetProducts();  
  5. }   
As Shawn Wildermuth describes in his article, this will work but it makes it difficult to handle the errors. IActionResult, an abstract base class, is more preferable as it has the flexibility to handle all the return types.

Run it!

Once we build the project, run it with IIS Express. It will run in a browser and look like the below screenshot

project
 
This will display a list of products in JSON format. You can prefer other tools, like Postman, Fiddler etc.
 
References

https://docs.asp.net/en/latest/intro.html
https://docs.asp.net/en/latest/tutorials/first-web-api.html
https://docs.asp.net/en/latest/migration/webapi.html
https://wildermuth.com/2016/05/10/Writing-API-Controllers-in-ASP-NET-MVC-6
 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now