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.
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:
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:
using System.Web.Http;
using System.Web.Http.SelfHost;
var hst = new HttpSelfHostConfiguration("http://localhost:8080");
hst.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(hst))
{
server.OpenAsync().Wait();
Console.WriteLine("To press enter for close.");
Console.ReadLine();
}
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..
function Add() {
var cont = {
name: $('#name').val(),
e_mail: $('#e_mail').val(),
ph: $('#ph').val()
};
$.ajax({
url: '/Api/Contacts',
type: 'POST',
data: JSON.stringify(cont),
contType: "application/json;charset=utf-8",
success: function (data) {
alert('successful addition of content');
GetContacts();
},
error: function (data) {
alert('problem generate to addition of content:' + data.responseText);
}
});
}
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.
function Delcont(id) {
$.ajax({
url: '/Api/Contacts/'+ id,
type: 'DELETE',
success: function (data) {
GetContacts();
},
error: function (data) {
alert('Problem generate for delition of content:' + data.responseText);
}
});
}
Updating the content with the Web API
The following is sample code for the updating of the content with the Web API:
function Updatecont(id) {
$.ajax({
url: '/Home/GetContactsById/' + id,
type: "GET",
success: function (response) {
$("#updatecontt").html(response);
},
error: function (data) {
$("#updatecont").html(data.responseText);
}
});
$(dialog).dialog('open')
}
dialog = $("#updatecont").dialog({
autoOpen: false,
resizable: false,
closeOnEscape: true,
show: "explode",
hide: "explode",
width: 350,
title: "Update Contact",
buttons: {
Update: function () {
var cont = {
name: $('#name').val(),
e_mail: $('#e_mail').val(),
Ph: $('#Ph').val()
};
$.ajax({
url: '/Api/Contacts/' + $('#Id').val(),
type: 'PUT',
data: JSON.stringify(cont),
contType: "application/json;charset=utf-8",
success: function (data) {
GetContacts();
},
error: function (data) {
alert('Problem generate on updation of content' + data.responseText);
}
});
$(dialog).dialog("close");
},
Cancel: function () {
$(dialog).dialog("close");
}
}
});