Getting Started With ASP.NET Web API


The Hyper Text Transfer Protocol (HTTP) is an application level protocol for distributed, collaborative and hypermedia information systems. As this protocol is foundation of data communication for World Wide Web so it is not only serving up web pages but also powerful platform for building APIs that expose services and Data. In the world mobile devices, browsers, web application and desktop application have HTTP library so API can access from almost any platform.

An API (Application Programming Interface) is the means by which third parties can write code that interfaces with other code. The ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. It gives response from the server as per request. This response based on Content Type in request and APIs use generally JSON and XML content type. It contains mostly ASP.NET MVC features so it’s easy to develop and use.

Using the Code

We create a new project for Web API to understand its implementation so follow below step.

Visual Studio - New Project, Web, then ASP.NET WEB Application.

After that choose Empty template from templates and select Web API checkbox to add folders and core references.

Create web API template
Figure 1: Create web API template

This empty web API template creates project with default folder structure and classes as in the following screenshot,

Web API project structure
Figure 2: Web API project structure

We use basically three folders from above structure which are App_Start, Controllers and Models. These folders have same role as I have ASP.NET MVC but little description about those:

  1. App_Start

    This folder contains those files which uses initial setting for web API such as WebApiConfig file. This file by default, defines routes for entire application but we can also define route on individual method.

  2. Controllers

    This folder contains C# class files that are controller classes. Controllers are responsible for handling end user interaction, manipulating the model and response data to other party as per requested Content type. Each controller class inherits an ApiController class. Each controller class name has "Controller" as a suffix on the class name. It is just a suggestion. It makes no difference whether we put controllers directly into this folder, into a subfolder of it, or anywhere else in the entire project or into another referenced project or assembly. Because we know that these are classes and all of them are compiled into the same assembly.

  3. Models

    This folder contains classes that define objects and the logic for interacting with the database or data items. The Model is used by request/response data and manipulate in controller. It is better to put model classes into a separate class library project because in real project this mode used as DTO (Data Transfer Object) so that Web application and other application use same model.

Now we create a model whose name is StudentModel under Models folder. The following code snippet shows this model.

  1. namespace WebAPISample.Models  
  2. {  
  3.     public class StudentModel  
  4.     {  
  5.         public string Name { getset; }  
  6.         public int Age { getset; }  
  7.     }  
  8. }  
After that we create an API controller whose name is HomeController. As web API designed to only have 4 calls, GET (one item / list items), POST, PUT and DELETE per entity type so in this example we see GET request call only. We create an action method to get student data as per the following code snippet,
  1. using System.Web.Http;  
  2. using WebAPISample.Models;  
  4. namespace WebAPISample.Controllers  
  5. {  
  6.     public class HomeController : ApiController  
  7.     {  
  8.         public StudentModel GetStudent()  
  9.         {  
  10.             return new StudentModel  
  11.             {  
  12.                 Name = "Sandeep",  
  13.                 Age = 27  
  14.             };  
  15.         }  
  16.     }  
  17. }  
Now we make a request from client/browser using http://localhost:56274/api/home/getStudent URL which returns response data as in the following screenshot,

Response Data in XML Format
Figure 3: Response Data in XML Format

In above request, we are using default routing of Web API where home is controller name and getStudent is action name.

As Web API is based on convention over configuration so getStudent action method is automatically made GET type request method. If we don’t use get as a prefix then we need to manually define method type as in the following code snippet,
  1. [HttpGet]  
  2. public StudentModel StudentData()  
  3. {  
  4.     return new StudentModel  
  5.     {  
  6.         Name = "Sandeep",  
  7.         Age = 27  
  8.     };  
  9. }  
The above code snippet gives same response data as shown in figure 3.

As these methods are responding data in XML format so how we can get response data in JSON format?

We just need to add the following code snippet in Register method under the WebAPIConfig class.
  1. config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
So entire class look like as:
  1. using System.Net.Http.Headers;  
  2. using System.Web.Http;  
  4. namespace WebAPISample  
  5. {  
  6.     public static class WebApiConfig  
  7.     {  
  8.         public static void Register(HttpConfiguration config)  
  9.         {  
  10.             // Web API configuration and services  
  12.             // Web API routes  
  13.             config.MapHttpAttributeRoutes();  
  15.             config.Routes.MapHttpRoute(  
  16.                 name: "DefaultApi",  
  17.                 routeTemplate: "api/{controller}/{action}/{id}",  
  18.                 defaults: new { id = RouteParameter.Optional }  
  19.             );  
  20.             config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
  21.         }  
  22.     }  
  23. }  
After that we get response in JSON format as in the following screenshot,

Response in JSON format
Figure 4: Response in JSON format

So remember some summary points,
  • The ASP.NET Web API is a framework for building web APIs on top of the .NET Framework.
  • ASP.NET Web API uses HTTP protocol which is application level protocol.
  • API stands for Application Programming interface.
  • ASP.NET web API has two Content Types for requested data one is XML and another is JSON.
  • ASP.NET web API default Content Type is XML for requested data.
  • GET” prefix in action name uses for GET call types method.