Getting Started With ASP.Net Web API

Introduction 

The ASP.Net Web API is a framework that helps to make it easy to create HTTP services to give the responses to the client depending on their request. HTTP services reaches a broad range of clients and also includes the browsers and mobile services. We use the web API content negotiation for sending the responses to clients based on their request. It means that a client requests data to be retuned as JSON or XML, and the web API framework returns the data based on the client request. 

Java Script Object Notation (JSON) is the easiest data interchange format. JSON is easy for clients to read and write.

Extensible Markup Language (XML) defines a set of rules for both human readable and machine readable data.

The Web API is a platform for building HTTP services where a request and response is generated with the HTTP protocol. The request can be GET, DELETE, POST and PUT and the response is done by the web API.

In short we can say that the Web API is:
  • an HTTP service
  • uses the HTTP as an application.
  • designed for reaching a broad range of clients.

Architecture of Web API


The WebAPI works on HttpRouteCollection and Route. The routing logic of MVC is used by the Web API team in webAPI. The independency of the web API is decided by the team so that it will not have the class dependencies of ASP.Net. It is hosted in the console and window services as self hosting.
 pic_2.jpg

Content negotiation in webAPI


Content negotiation is a process, in other words used for selecting the best representation of the response from which there are many possible representations for responses. The webAPI framework implements the content negotiation. For this reason clients can request the data with a specific media type.

 

By default the webAPI returns the response in JSON format.
 
Here is a format of content negotiation:
pic6.jpg

Implementation of WebAPI


Here we see the implementation of web API.

We create a class. This class derives from the ApiController. We defines the method in WebAPI and these methods are maps to the HTTP methods. If the method have GET prefix it means that the response gives based on the GET request. you ensure that whatever action you implement with the request.

Hosting of a Web API


There are two types of hosting:

First is Web hosting: In this category hosting is done using ASP.Net on IIS.

Second is Self hosting: This category hosts itself; that means it is hosted in a separate Windows process. One example is Console Application.

Example

The following is sample code for the self hosting:

  1. using System.Web.Http;  
  2. using System.Web.Http.SelfHost;       
  3. var hst = new HttpSelfHostConfiguration("http://localhost:8080");  
  4. hst.Routes.MapHttpRoute(  
  5.     "API Default""api/{controller}/{id}",  
  6.     new { id = RouteParameter.Optional });  
  7. using (HttpSelfHostServer server = new HttpSelfHostServer(hst))  
  8. {  
  9.     server.OpenAsync().Wait();  
  10.     Console.WriteLine("To press enter for close.");  
  11.     Console.ReadLine();  
  12. }   

Adding the content with web API

This code is used to add the new content with API. In this code we create the jQuery, and this sends a request for the URL to the webAPI. And it passes the content information to the HTTP as a JSON object..

  1. function Add() {  
  2.     var cont = {  
  3.         name: $('#name').val(),  
  4.         e_mail: $('#e_mail').val(),  
  5.         ph: $('#ph').val()  
  6.     };  
  7.     $.ajax({  
  8.         url: '/Api/Contacts',  
  9.         type: 'POST',  
  10.         data: JSON.stringify(cont),  
  11.         contType: "application/json;charset=utf-8",  
  12.         success: function (data) {  
  13.             alert('successful addition of content');  
  14.             GetContacts();  
  15.         },  
  16.         error: function (data) {  
  17.             alert('problem generate to addition of content:' + data.responseText);  
  18.         }  
  19.     });  
  20. }   

Content delete with web API

This code is used to delete the content with the API.  In this code we create the jQuery that sends the request for the URL to the webAPI. Here we use the type DELETE to delete the content.

  1. function Delcont(id) {        
  2.     $.ajax({  
  3.         url: '/Api/Contacts/'+ id,  
  4.         type: 'DELETE',  
  5.         success: function (data) {  
  6.             GetContacts();  
  7.         },  
  8.         error: function (data) {  
  9.             alert('Problem generate for delition of content:' + data.responseText);  
  10.         }  
  11.     });  
  12. }

Updating the content with the Web API

The following is sample code for the updating of the content with the Web API:

  1. function Updatecont(id) {  
  2.     $.ajax({  
  3.         url: '/Home/GetContactsById/' + id,  
  4.         type: "GET",  
  5.         success: function (response) {  
  6.             $("#updatecontt").html(response);                
  7.         },  
  8.         error: function (data) {  
  9.             $("#updatecont").html(data.responseText);  
  10.         }  
  11.     });  
  12.     $(dialog).dialog('open')  
  13. }  
  14. dialog = $("#updatecont").dialog({  
  15.         autoOpen: false,  
  16.         resizable: false,  
  17.         closeOnEscape: true,  
  18.         show: "explode",  
  19.         hide: "explode",  
  20.         width: 350,  
  21.         title: "Update Contact",  
  22.         buttons: {  
  23.             Update: function () {  
  24.                 var cont = {  
  25.                     name: $('#name').val(),  
  26.                     e_mail: $('#e_mail').val(),  
  27.                     Ph: $('#Ph').val()  
  28.                 };  
  29.             $.ajax({  
  30.                 url: '/Api/Contacts/' + $('#Id').val(),  
  31.                 type: 'PUT',  
  32.                 data: JSON.stringify(cont),  
  33.                 contType: "application/json;charset=utf-8",  
  34.                 success: function (data) {  
  35.                     GetContacts();  
  36.                 },  
  37.                 error: function (data) {  
  38.                     alert('Problem generate on updation of content' + data.responseText);  
  39.                 }  
  40.             });  
  41.             $(dialog).dialog("close");  
  42.         },  
  43.         Cancel: function () {  
  44.             $(dialog).dialog("close");  
  45.         }  
  46.     }  
  47. });  


Similar Articles