Introduction
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.
Figure 1: Create web API template
This empty web API template creates project with default folder structure and classes as in the following screenshot,
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:
- 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.
- 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.
- 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.
- namespace WebAPISample.Models
- {
- public class StudentModel
- {
- public string Name { get; set; }
- public int Age { get; set; }
- }
- }
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,
- using System.Web.Http;
- using WebAPISample.Models;
-
- namespace WebAPISample.Controllers
- {
- public class HomeController : ApiController
- {
- public StudentModel GetStudent()
- {
- return new StudentModel
- {
- Name = "Sandeep",
- Age = 27
- };
- }
- }
- }
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,
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,
- [HttpGet]
- public StudentModel StudentData()
- {
- return new StudentModel
- {
- Name = "Sandeep",
- Age = 27
- };
- }
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.
- config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
So entire class look like as:
- using System.Net.Http.Headers;
- using System.Web.Http;
-
- namespace WebAPISample
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
-
-
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{action}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
- }
- }
- }
After that we get response in JSON format as in the following screenshot,
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.