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).
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.
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.
Visual studio scaffold's default actions whenever we create a new web API Controller Class.
- [Route("api/[controller]")]
- public class ProductController : Controller
- {
-
- [HttpGet]
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
- [HttpGet("{id}")]
- public string Get(int id)
- {
- return "value";
- }
-
-
- [HttpPost]
- public void Post([FromBody]string value)
- {
- }
-
-
- [HttpPut("{id}")]
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- [HttpDelete("{id}")]
- public void Delete(int id)
- {
- }
- }
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.
- public class Product
- {
- public int ProductId { get; set; }
- public string Name { get; set; }
- public decimal Price { get; set; }
- public DateTime CreatedDate { get; set; }
- }
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.
- public static List<Product> GetProducts()
- {
- return new List<Product>()
- {
- new Product {ProductId=1, Name="Product 1",Price=100,CreatedDate=DateTime.Now },
- new Product {ProductId=2, Name="Product 2",Price=200,CreatedDate=DateTime.Now },
- new Product {ProductId=3, Name="Product 3",Price=300,CreatedDate=DateTime.Now },
- new Product {ProductId=4, Name="Product 4",Price=400,CreatedDate=DateTime.Now },
- new Product {ProductId=5, Name="Product 5",Price=500,CreatedDate=DateTime.Now },
- };
- }
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.
- [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.
- [HttpGet("{id}")]
- public string Get(int id)
- {
- return "value";
- }
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.
- [HttpGet]
- public List<Product> Get()
- {
- return ProductService.GetProducts();
- }
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
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