Quick start to create RESTful Web API in ASP.NET Core

As ASP.NET MVC and Web.APIs are almost same, Microsoft combined 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. They are 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).

Enter a name of 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.

 "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0"
  }

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 default actions, whenever we create a new web API Controller Class.
[Route("api/[controller]")]
public class ProductController : Controller
{
    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}
If you had observed, API Controller is inheriting Controller base class instead of ApiController. ASP.NET Core make it happen.

Add a model class

Add new folder in the project named it "Models". Now, right click on the Models folder 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 run time with the name of the controller or action, respectively to which the attribute has been applied. This will reduce 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 introduced with the various [Http{Verb}] attributes so you can succinctly state that a GET request with and ‘id’ will be handled by the Get method.
[HttpGet("{id}")]
public string Get(int id)
{
    return "value";
}

To return a list of products from webapi controller, replace Get() action with below code. ProductService.GetProducts() will returns list of products.
[HttpGet]
public List<Product> Get()
{
    return ProductService.GetProducts();
}
As Shawn Wildermuth describes in his article, this will works but it makes it difficult to handle errors. IActionResult is an abstract base class more preferable as its has flexibility to handle all return types.

Run it!

Once we build the project, run project with IIS Express. It will run in a browser and looks like below. This will displays a list of products in json format. You can prefer other tools like Postman, Fiddler etc.

Next post, I'm going to explore how to configure dependency injection in ASP.NET Core.

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