ASP.NET Web API in MVC tutorial

Introduction to ASP.NET Web API

ASP.NET Web API is one of new exciting feature of ASP.NET MVC 4. It is ideal framework for creating RESTful applications with .NET framework. It makes easy to build HTTP services and reach large number of clients like browsers and mobile devices. You can use XML or JSON or something else with these API. See more details on RESTful CRUD operations using ASP.NET Web API.

ASP.NET Web API allows you create api or http based service or client endpoints.yujo Although it comes with ASP.NET MVC4, it is much flexible framework to develop REST and AJAX API for HTML5, ASP.NET Web forms, client server desktop applications. Unlike WCF Web API does not required much configuration settings and you can host it in your own applications.


Below points can help you to choose WCF or ASP.NET Web API

  • If you want to create resource based services and need to take full advantage of HTTP like cache control for browsers, transfer different kind of content types like documents, images, HTML pages ASP.NET Web API should be selected.
  • If you have heterogeneous clients for same service and needs to call service using different protocols like netTCPBinding, netNamedPipeBinding, wsHttpBinding WCF is the obvious choice.
  • If you have special requirements like CallBackContract, One way communication or queuing then WCF should be selected.

In this article we will create a simple ASP.NET web api application in MVC. This application will read the data from Customers.xml file and show it on web page using jQuery.

Implementation of ASP.NET Web API in MVC

  1. Create new ASP.NET Web API

    Open visual studio and click on File -> New Project -> Select ASP.NET MVC4 Web Application
    Name the application as NorthwindWebApi
    From next window select Web API template and Razor as ViewEngine.
    New ASP.Net MVC4 Project
  2. Customer Model

    In ASP.NET MVC, Model manages properties and data of application and it contains all application logic like business logic, validation logic or data access logic. Model binders helps controller to keep its code cleanly separated from actual request and its environment. See more on ASP.NET MVC Application Request life cycle

    ASP.NET web api will produce serialized data of model to JSON, XML or some other format. It also writes HTTP Response messages with serialized data. Client can use GET verb to get data in specific format like JSON or XML by setting Accept header HTTP Request message.

    Create a new class in Model folder. Name it as Customer

    Customer Model will represent Customer entity from datastore. Add below properties to Model.
        namespace NorthwindWebApi.Models
            public class Customer
                public string CustomerID { get; set; }
                public string CompanyName { get; set; }
                public string City { get; set; }
  3. Customer ApiController

    The controllers in Web API inherits from ApiController class instead of Controller. The major difference between them is, actions from ApiController returns data and not Views. See difference between ApiController and Controller.
    Add Customer ApiController by right click on Controllers folder from Solution Explorer. Select Add -> Controller. Name it as CustomerController
    From next window select Empty Api Controller.
    ASP.NET Web API controller
    Add below code to CustomerController. It has two methods GetAllCustomers which returns all the customers from Customer.xml and GetCustomer which takes id as input parameter and return its customer details.
    using NorthwindWebApi.Models;
    using System.Xml.Linq;
    using System.Collections;  
    namespace NorthwindWebApi.Controllers
        public class CustomerController : ApiController
            public List<customer> GetAllCustomers()
                List<Customer> customers = new List<Customer>();
                XDocument doc = XDocument.Load("C:\\Customers.xml");
                foreach (XElement element in doc.Descendants("DocumentElement")
                    Customer customer = new Customer();
                    customer.CustomerID = element.Element("CustomerID").Value;
                    customer.CompanyName = element.Element("CompanyName").Value;
                    customer.City  = element.Element ("City").Value;
                return customers;
            public Customer GetCustomer(int id)
                Customer customer = new Customer();
                XDocument doc = XDocument.Load("C:\\Customers.xml");
                XElement element = doc.Element("DocumentElement")
                                    SingleOrDefault(x => x.Value == id.ToString());
                if (element != null)
                    XElement parent = element.Parent;
                    customer.CustomerID =
                    customer.CompanyName =
                    customer.City =
                    return customer;
                    throw new HttpResponseException
                        (new HttpResponseMessage(HttpStatusCode.NotFound));
  4. Customer View

    As Web API does not return View or ActionResult, for this tutorial you can use default Index.cshtml under Views -> Home folder.
    Replace html from Index.cshtml with below code which shows all customers by retrieving JSON through jQuery call to Customer Web API.
    <div id="body">
    <section class="content-wrapper main-content clear-fix">
            <h2>All Customers</h2>
            <table id="customers" style="border: 1px solid black;"  ></table> 
    @section scripts {
        var apiCustomers = 'api/customer';
        $(document).ready(function () {
            // Send an AJAX request
            var rows = '';
                function (data) {
                    $.each(data, function (key, val) {
                        var customerURL = apiCustomers + '/' + val.CustomerID;
                        rows = rows + '<tr style="border: 1px solid black;"><td>  ' +
                        '<a style="color: Blue; font-weight:bold; font-size:15px"'
                           + 'href="' + customerURL + '">' + val.CustomerID + '</a>' +
                            '</td><td>' + val.CompanyName + 
                            '</td><td>' + val.City + '</td></tr>';

    It shows all the customers and link to each customer.
    ASP.NET Web API All Customers

    Now click on CustomerID link to see Customer details.

    ASP.NET Web API Get Customer Details
    As we haven't implemented any HTML view for customer details it shows customer details in browser. Depending on your browser it shows the customer details Chrome and Firefox will show xml whereas Internet Explorer will show it in JSON. It is because the request attribute Accept-headers send by browsers are different.

Download source code.

Jobs in Mumbai

Web Developers - AAVID CODE-1
written English. Proficient in customizing and developing websites in WordPress, Joomla, Drupal CMS. SQL ...
Web Developers - Cyberindigo Net Pvt Ltd
Expertise in ASP.Net development Expertise in C#, Ease with Javascript and VB Script ... ASP.Net,,Ajax is required. 3. Understanding of...
Web Developers - C-MOTS Internet Technologies Pvt. Ltd.
The candidate should be an expert web technologies (PHP, mySQL, JavaScript, AJAX, HTML, CSS). Preference shall be given to candidates with the...
Web Developers - Basil Life Care Pvt Ltd.
C#/VB.Net, Asp.Net SQL Server Crystal Reports Silverlight Knowledge of Cloud Computing will be ...
Web Developers - eXEGESIS Infotech (I) Pvt LTd
1. Should have strong experience on, and SQL Server. 2. Should have worked ...

Latest Blogs on

ASP.NET MVC Model Example
This article describes you about what is ASP.NET Model, example of how to use and bind model data, how to make GET or Post request using model.
Getting Started Tutorial with ASP.NET MVC
This article gives you step by step tutorial to create first ASP.NET MVC application using feature like Controller and View.
ASP.NET MVC Controller, Action Method and ActionResult
n this article I am going to explain about ASP.NET MVC Controller, its Action Method and Action Result. And how to create and use controller in MVC application
Hello World Example With AngularJS and ASP.NET MVC
This article equips you to create your first hello world example using AngularJS framework and ASP.NET MVC.
How to Use Areas in ASP.NET MVC
This article describe about Areas in ASP.NET MVC application and organize application structure in better and simple way.

Speak your mind :
Leave a comment for this article on