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

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

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; }

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));

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.

Speak your mind :
Leave a comment for this article on
User profile picture on

by Vijay at 1/22/2019 8:18:00 AM
I got one project where the same architecture we are following but at the time of calling WebAPO from MVC I am getting an error of internal server issues (ExceptionMessage: "Object reference not set to an instance of an object."). Don't know why it's happening.
post comment on
User profile picture on

by Vijay at 1/22/2019 8:22:00 AM
I got one project where the same architecture we are following but at the time of calling WebAPO from MVC I am getting an error of internal server issues (ExceptionMessage: "Object reference not set to an instance of an object."). Don't know why it's happening.
post comment on