Click here to Skip to main content
14,210,255 members
Click here to Skip to main content
Article
Posted 4 Jan 2016

Tagged as

Stats

15.3K views
11 bookmarked

Creating ASP.NET Web API and consuming it through HTML Clients – Part I

,
Rate this:
3.29 (4 votes)
Please Sign up or sign in to vote.
3.29 (4 votes)
5 Jan 2016     CPOL    
Creating an ASP.NET Web API from scratch and consuming it through HTML clients.

Introduction

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.

Background

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. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

Using the code

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)

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

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 below class named Product as shown in below screen caps.

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

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}

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

 public interface IProductManager
    {
        List<Product> GetAll();
        Product Get(int id);
        Product Add(Product product);
        void Remove(int id);
        bool Update(Product product);
    }
 public class ProductManager: IProductManager
    {
        List<Product> products = new List<Product>();
        private int _autoProductId = 1;
 
        public ProductManager()
        {
            Add(new Product { Name = "Pen", Type = "Stationary", Description = "Pen from Lexi Company", Price = 10 });
            Add(new Product { Name = "Ball", Type = "Sports", Description = "Ball from Hedley", Price = 65 });
            Add(new Product { Name = "Battery", Type = "Electronics", Description = "Duracell batteries", Price = 20 });
            Add(new Product { Name = "Books", Type = "Stationary", Description = "Academic books", Price = 2000 });
            Add(new Product { Name = "Gym Bag", Type = "Sports", Description = "Gym Bag from Reebok", Price = 1500 });
        }
 
        public List<Product> GetAll()
        {
            return products;
        }
 
        public Product Get(int id)
        {
            var product = products.Find(p => p.Id == id);
            return product;
        }
 
        public Product Add(Product product)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            product.Id = _autoProductId++;
            products.Add(product);
            return product;
        }
 
        public void Remove(int id)
        {
            products.RemoveAll(p => p.Id == id);
        }
 
        public bool Update(Product product)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            int index = products.FindIndex(p => p.Id == product.Id);
            if (index == -1)
            {
                return false;
            }
            products.RemoveAt(index);
            products.Add(product);
            return true;
        }
    }

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 select 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

public class ProductController : ApiController
    {
        static readonly IProductManager prodManager = new ProductManager();
 
        //Get All Products
        [HttpGet]
        public List<Product> GetAllProducts()
        {
            return prodManager.GetAll();
        }
        //Get Product by id
        [HttpGet]
        public Product GetProductById(int id)
        {
            var product = prodManager.Get(id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.OK);
            }
            return product;
        }
        //Add Product
        [HttpPost]
        public Product AddProduct(Product product)
        {
            product = prodManager.Add(product);
            return product;
        }
        //Update Product
        [HttpPut]
        public void UpdateProduct(Product product)
        {
            if (!prodManager.Update(product))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }
        //Delete Product
        [HttpDelete]
        public void DeleteProduct(int id)
        {
            Product product = prodManager.Get(id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            prodManager.Remove(id);
        }

Points of Interest

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

What do you Think?

Dear Reader,

If you have any questions or suggestions please feel free to email me or put your thoughts as comments below. I would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Learning

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dipendra Singh Shekhawat
United States United States
Hello Guys! I am Dipendra Shekhawat, Software Developer with more than 5 years of experience. My skills mostly revolve around technologies like ASP.NET, C#, SQL, JQuery, JavaScript, HTML, CSS, AJAX, WCF, Web Services. I have started my blog - http://dipendrashekhawat.com/ to share my knowledge and help others to learn.

Comments and Discussions

 
QuestionSource code Pin
tdt2314-Jan-16 6:25
membertdt2314-Jan-16 6:25 
AnswerRe: Source code Pin
Dipendra Singh Shekhawat15-Jan-16 22:27
memberDipendra Singh Shekhawat15-Jan-16 22:27 
QuestionError in code Pin
Member 113178245-Jan-16 8:03
memberMember 113178245-Jan-16 8:03 
AnswerRe: Error in code Pin
Dipendra Singh Shekhawat5-Jan-16 17:31
memberDipendra Singh Shekhawat5-Jan-16 17:31 
GeneralRe: Error in code Pin
Dewey5-Jan-16 21:49
memberDewey5-Jan-16 21:49 
You could avoid these silly issues, and this is pathetic, if you simply added the freaking project source code!

If you really did this and tested it, the project should be just sitting there, ready to be zipped up!

This is so simple, but anyone needing the code would benefit greatly!

BTW, how do you get a typo from copy & paste of generated code?
QuestionHttp attributes - which assembly reference should you use? Pin
Eagle324-Jan-16 10:29
memberEagle324-Jan-16 10:29 
AnswerRe: Http attributes - which assembly reference should you use? Pin
Dipendra Singh Shekhawat4-Jan-16 23:46
memberDipendra Singh Shekhawat4-Jan-16 23:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190618.1 | Last Updated 6 Jan 2016
Article Copyright 2016 by Dipendra Singh Shekhawat
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid