ASP.Net MVC 4 is packed up with a new project template called Web API – 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 you will find basics of creating an ASP.Net MVC 4 Web API.
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.
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.
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.