Quick Start Guide to Create a RESTful Web API in ASP.NET Core

Datetime:2016-08-23 04:42:37          Topic: ASP.NET  REST           Share

As ASP.NET MVC and web APIs are almost same, Microsoft combined both in its 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 the ASP.NET Core MVC. In this post, we will create simple web API (REST) and test it from the 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 the dialog box, select the Web API template and click OK. This will generate default ASP.NET Core WEB API project.

Let's see what has been changed in the project.json file.

As ASP.NET Core provides a common platform for MVC and web APIs, 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, so 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 scaffolds 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 the Controller base class instead of APIController. (only ASP.NET Core has guts to make it happen).

Add a Model Class

Add a new folder in the project named "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 the 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 runtime 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 the WebAPI controller, replace the Get() action with the code below. ProductService.GetProducts() will return a list of products.

[HttpGet]
public List<Product> Get()
{
    return ProductService.GetProducts();
}

As Shawn Wildermuth described in his article, this will work, but it makes it difficult to handle errors. IActionResult is a more preferable abstract base class because it has the flexibility to handle all return types.

Run It!

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

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





About List