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

    A 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.

    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.

Latest Jobs in

Web Developers - Client of Talent Transformers
Multiple openings for .NET developers (Net, ASP.Net,C#,SQL Server) with 4 to 8 years of ... Position Title .NET developers (Net, ASP.Net,C#,SQL...
Web Developers - S2C Consulting Pvt Ltd
, SharePoint Developer, SharePoint 2007, SharePoint 2010, SharePoint 2013, Office 365 App, NET framework, ASP.NET ...
Computer Software Engineers, Applications - CerebralLink Limited
, SQL Plus, K Shell, C Shell, Perl, Cognos, BusinessObjects, MicroStrategy, Tableau, Pentaho, JasperSoft ...
Computer Software Engineers, Applications - Teamware Solutions Pvt Ltd
Skills Required: PL/SQL, Oracle 11g, Good understanding of Data warehousing concepts; Unix ...
Web Developers - Client of Talent Transformers
Opportunity for an ASP.NET MVC 4 consultants with 4 to 8 years of experience to be based out ... WCF.NET – designed and developed service using wcf...

Latest Blogs on

Implementing Finalize and Dispose(.NET Framework) in C#
This article describes about implementing between dispose and finalize methods for
User Defined Functions in SQL Server
This article talks about user defined functions (UDF) in SQL Server, its benefits, type of UDF and UDF parameters.
IIS settings to improve ASP.NET Website Performance
This article helps you to understand required IIS settings to improve ASP.NET Website Performance.
ASP.NET Website Performance Improvement Tips
This article give you some of the best tips to improve your ASP.NET Website performance.
Getting started with ASP.NET Web API
This article helps you to understand ASP.NET Web API concepts

Speak your mind :
Leave a comment for this article on