Build and Consume an ASP.Net MVC 4 Web API

ASP.Net MVC 4 is packed up with a new project template called Web API. In the technology world, an API is defined as an exposed application interface, which can be consumed by different client applications in order to perform data transfers. Similarly ASP.Net MVC 4 Web API application can be used to create HTTP services, which can be consumed by a wide range of clients from mobile browser applications to Windows Forms applications.

In this article I will give an overview on creating an ASP.Net MVC 4 Web API and consuming it from client applications.

New ASP.NET MVC 4 Project
Fig 1.0 New ASP.NET MVC 4 Project

How Different it is from .NET Web Services

When I first heard about the Web API feature, instantly my thought was about how different it would be from a regular XML web service. Following are a few things in which Web API is different from web services.

1. Works over plain HTTP protocol as HTTP services without SOAP.

2. Content Negotiation – Automatically responds back in plain XML or in JSON format based on the Accept Header in the client request.

3. Allows implementing REST (Representative State Transfer) architecture. URL can be used to define the actions and parameters.

4. Support for HTTP verbs.

a. GET


c. PUT


Asp.Net MVC Application as Web API

When you create an ASP.Net MVC Web API application you will not see any considerable difference between an ASP.NET Web API and a normal MVC application because both exhibit the same MVC architecture. So it is important to know what is extra for a Web API than a normal MVC application.


Though both the application types are driven through controller, the Web API controller classes inherit from the ApiController class. The action methods return only data instead of Views and also they are mapped to a particular HTTP operation (get, post, put or delete) based on their prefix.

When a Web API project is created a default controller class named ValuesController.cs will be added under the controller folder.


The Web API request routing is registered in this class. It allows the application to differentiate if the request is for the MVC controller action or for Web API controller action. Below is a sample code to register Web API action requests.

public static class WebApiConfig


        public static void Register(HttpConfiguration config)



                name: "DefaultApi",

                routeTemplate: "api/{controller}/{id}",

                defaults: new { id = RouteParameter.Optional }




Creating a Sample Web API Application

Open Visual Studio 2012 and create an ASP.Net MVC 4 Web API application and name it WebApiDemo. Now go and delete the default ValuesController.cs and add the Model named Car.cs. Following is the Car.cs class source code.

namespace WebApiDemo.Models


    public class Car


        public int RegistrationNumber { get; set; }

        public string Company { get; set; }

        public string Color { get; set; }

        public string Type { get; set; }



Create the ApiController class for the Web API. Right click on the Controller folder and select Add Controller. Make sure that the template selected is Empty API Controller. Add the Get and Post methods.

namespace WebApiDemo.Controllers


    public class CarController : ApiController


        List<Car> m_Car = new List<Car>()


           new Car()


               RegistrationNumber = 1000,

               Company = "Ferrari",

               Color = "Red",

               Type = "Sport"


           new Car()


               RegistrationNumber = 1001,

               Company = "Mercedes",

               Color = "White",

               Type = "Comfort"


           new Car()


               RegistrationNumber = 1002,

               Company = "Audi",

               Color = "Black",

               Type = "Luxury"




        public HttpResponseMessage GetCar(int registrationNumber)


            var car = from c in m_Car

                      where c.RegistrationNumber == registrationNumber

                      select c;


            return Request.CreateResponse<Car>(HttpStatusCode.OK, car.FirstOrDefault());



        public HttpResponseMessage PostCar(Car car)




            return Request.CreateResponse<Car>(HttpStatusCode.Created, car);




In the above code, method GetCar fetches a car based on the registration number and PostCar adds a new car to the repository.

Consume in a Web Application Through JQuery

Create a web application, may be a MVC application itself and in the .cshtml file go and add the following Ajax request to add a car.


    <script src="~/Scripts/jquery-1.7.1.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $("#btnAddCarr").click(function () {



                    url: "http://localhost:53160/api/car/",

                    type: "POST",

                    dataType: "json",

                    data: JSON.stringify(car),

                    contentType: "application/json;charset=utf-8",

                    success: function (data) {

                        alert('Car is added successfully!');


                    error: function () {

                        alert('An error occured while adding a car!');






        function AddCar() {

            var car = {

                RegistrationNumber: 1003,

                Company: "BMW",

                Color: "Blue",

                Type: "Sport"





Consume in a Windows Forms Application

In order to consume from the Windows Forms application or from a C# code behind file then the HttpClient class can be used. Following is the C# code to fetch the data from the Web API that we created earlier.

private async void GetCars()


            using (var client = new HttpClient())


                using (var response = await client.GetAsync("http://localhost:53160/api/car/?regnumber=1001"))


                    if (response.IsSuccessStatusCode)


                        var carJsonString = await response.Content.ReadAsStringAsync();





Hope this article was informative. Happy reading!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read