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

b. POST

c. PUT

d. DELETE

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.

ApiController

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.

WebApiConfig.cs

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)

        {

            config.Routes.MapHttpRoute(

                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)

        {

            m_Car.Add(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.

<header>

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

    <script type="text/javascript">

        $(document).ready(function () {

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

                AddCar();

                $.ajax({

                    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"

            };

        }

    </script>

</header>

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!



Related Articles

Comments

  • Its always necessary keep your teeth clean

    Posted by tamrinnalon on 04/28/2013 02:18am

    A tooth (plural teeth) is a small, calcified, whitish structure ground in the jaws (or mouths) of various vertebrates and used to break down food. Some animals, strikingly carnivores, also partake of teeth in behalf of hunting or for defensive purposes. The roots of teeth are covered by gums. Teeth are not made of bone, but rather of multiple tissues of varying density and hardness. The general systematize of teeth is similar across the vertebrates, although there is sizeable modifying in their shape and position. The teeth of mammals drink esoteric roots, and this design is also initiate in some fish, and in crocodilians. In most teleost fish, regardless how, the teeth are attached to the outer surface of the bone, while in lizards they are attached to the inner come up of the jaw during the same side. In cartilaginous fish, such as sharks, the teeth are joined around tough ligaments to the hoops of cartilage that form the jaw.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: August 14, 2014 Data protection has long been considered "overhead" by many organizations in the past, many chalking it up to an insurance policy or an extended warranty you may never use. The realities of today makes data protection a must-have, as we live in a data-driven society -- the digital assets we create, share, and collaborate with others on must be managed and protected for many purposes. Check out this webcast and join Seagate Cloud Systems and Solutions Chief …

  • Live Webinar Tuesday, August 26, 2014 1:00 PM EDT Customers are more empowered and connected than ever, and the customer's journey has grown more complex. Their expectations are growing and trust is diminishing as they may interact with multiple brands through web, mobile and social channels. Considering 70% of the buying process in a complex sale is already complete before prospects are willing to engage with a live salesperson -- it's critical to understand your customers and anticipate their needs.* …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds