Creating ASP.NET Web API And Consuming It Through HTML Clients - Part 1

ASP.NET Web API is very powerful and in demand technology.

Today, we would be dealing with creating ASP.NET Web API and consume it through HTML client. Due to length and depth of this article I have divided it into two parts. In part I, our focus will be to create ASP.NET Web API project and configure all necessary stuff. Whereas in part II, we will be looking at how to consume this API.

  1. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. 
  2. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

Adding an ASP.NET Web API controller to your application is almost exactly like adding an ASP.NET MVC controller. You can either add a Web API in the existing MVC project or can create a separate Web API project.

Let’s start creating a new Web API project.

Start Visual Studio (I have used VS 2012 in this example) and follow the steps below:

  1. Select New Project and choose ASP.NET MVC 4 Web Application from the list of project templates. Name the project “WebApiDemo”.
  2. In the Project Template dialog, select Web API and click Ok.

Creating ASP.net Web API project                                                Creating ASP.net Web API project

As soon as you click Ok, a default web API project is created. In the controller folder a file named ValuesController.cs is created. This is the default Web API service fie added. Either you can modify this or you can add a new API Controller.

In the Global.asax file a default routing map is also added in the RegisterRoutes function (Just press F12 on RegisterRoutes function. It will take you to the function definition).

  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.     routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new  
  5.     {  
  6.         controller = "Home", action = "Index", id = UrlParameter.Optional  
  7.     });  
  8. }  

You can modify this file to reflect any configuration changes you want to make for the application. The default contains a single route as an example to get you started.

Let us create our own Product API Controller instead of modifying the existing ValuesController.cs.

Before creating the Product Api controller we will be creating the Product model and Product Manager classes. These classes will be used in the Product API controller to perform CRUD (Create, Read, Update, and Delete) operations.

Product Model

In Solution Explorer, right-click the Models folder then add the following class named Product as in the following screenshot,

Creating a model class in ASP.NET Web API project
Creating a model class in ASP.NET Web API project.
Creating a model class in ASP.NET Web API project

Creating a model class in ASP.NET Web API project,

  1. public class Product  
  2. {  
  3.     public int Id  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string Name  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string Type  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string Description  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public decimal Price   
  24.       
  25.         get;  
  26.         set;  
  27.     }  
  28. }  

Similarly add the following Interface and class in the same Model folder.

  1. public class IProductManager  
  2. {  
  3.     List < Product > GetAll();  
  4.     Product Get(int id);  
  5.     Product Add(Product product);  
  6.     void Remove(int id);  
  7.     bool Update(Product product);  
  8. }  
  9. public class ProductManager: IProductManager  
  10. {  
  11.     List < Product > products = new List < Product > ();  
  12.     private int _autoProductId = 1;  
  13.     public ProductManager()   
  14.     {  
  15.         Add(new Product   
  16.         {  
  17.             Name = "Pen", Type = "Stationary", Description = "Pen from Lexi Company", Price = 10  
  18.         });  
  19.         Add(new Product  
  20.         {  
  21.             Name = "Ball", Type = "Sports", Description = "Ball from Hedley", Price = 65  
  22.         });  
  23.         Add(new Product  
  24.         {  
  25.             Name = "Battery", Type = "Electronics", Description = "Duracell batteries", Price = 20  
  26.         });  
  27.         Add(new Product  
  28.         {  
  29.             Name = "Books", Type = "Stationary", Description = "Academic books", Price = 2000  
  30.         });  
  31.         Add(new Product   
  32.         {  
  33.             Name = "Gym Bag", Type = "Sports", Description = "Gym Bag from Reebok", Price = 1500  
  34.         });  
  35.     }  
  36.     public List < Product > GetAll()   
  37.     {  
  38.         return products;  
  39.     }  
  40.     public Product Get(int id)   
  41.     {  
  42.         var product = products.Find(p => p.Id == id);  
  43.         return product;  
  44.     }  
  45.     public Product Add(Product product)  
  46.     {  
  47.         if (product == null)   
  48.         {  
  49.             throw new ArgumentNullException("product");  
  50.         }  
  51.         product.Id = _autoProductId++;  
  52.         products.Add(product);  
  53.         return product;  
  54.     }  
  55.     public void Remove(int id)  
  56.     {  
  57.         products.RemoveAll(p => p.Id == id);  
  58.     }  
  59.     public bool Update(Product product)  
  60.     {  
  61.         if (product == null)  
  62.         {  
  63.             throw new ArgumentNullException("product");  
  64.         }  
  65.         int index = products.FindIndex(p => p.Id == product.Id);  
  66.         if (index == -1)  
  67.         {  
  68.             return false;  
  69.         }  
  70.         products.RemoveAt(index);  
  71.         products.Add(product);  
  72.         return true;  
  73.     }  
  74. }  

Now we are ready to create our Product Web API controller. Before adding the new API controller delete the file named ValuesController.cs within Controllers folder from the project.

Add a Web API Controller

In Solution Explorer, right-click the Controllers folder. Select Add and then Controller.

Creating a controller class in ASP.NET Web API project

Creating a controller class in ASP.NET Web API project,

In the Add Controller dailog, name the controller ProductController. In the Template drop-down list, select Empty API Controller and click Add.

Adding a model class in ASP.NET Web API project

Adding a model class in ASP.NET Web API project,

Add the following code in the ProductController.cs class,

  1. public class ProductController: ApiController   
  2. {  
  3.  static readonly IProductManager prodManager = new ProductManager(); //Get All Products  
  4.  [HttpGet] public List<Product> GetAllProducts()  
  5.         {   
  6.           return prodManager.GetAll();   
  7.         } //Get Product by id   
  8.   [HttpGet] public Product GetProductById(int id)   
  9.   {   
  10.     var product = prodManager.Get(id); if (product == null)   
  11.     {   
  12.       throw new HttpResponseException(HttpStatusCode.OK);   
  13.     }   
  14.     return product;   
  15.   } //Add Product   
  16.   [HttpPost] public Product AddProduct(Product product)   
  17.   {   
  18.     product = prodManager.Add(product);   
  19.     return product;   
  20.   }   
  21.   //Update Product   
  22.   [HttpPut] public void UpdateProduct(Product product)   
  23.   {   
  24.     if (!prodManager.Update(product))   
  25.     {   
  26.       throw new HttpResponseException(HttpStatusCode.NotFound);   
  27.     }   
  28.   }   
  29.   //Delete Product   
  30.   [HttpDelete] public void DeleteProduct(int id)   
  31.   {   
  32.     Product product = prodManager.Get(id);  
  33.     if (product == null)   
  34.     {   
  35.       throw new HttpResponseException(HttpStatusCode.NotFound);   
  36.     }   
  37.     prodManager.Remove(id);   
  38.   }   
  39. }  

Congratulations, at this point of time we have successfully created our Web API project. In out next article we would be covering how we can consume this Web API.


Similar Articles