Use XMLHttpRequest to Call ASP.NET Web API
Most of the times developers use jQuery $.ajax() to call ASP.NET Web API from
the client side script. At times, however, you may need to use plain JavaScript
to invoke the Web API. Consider a situation wherein you wish to call Web API
from HTML5 Web Worker. Now, you can't use jQuery to accomplish your task because
DOM access is not allowed inside a web worker. Another reason might be that your
project don't have any dependency on jQuery or such libraries. Luckily, calling
a Web API using XMLHttpRequest object and plain JavaScript is not hard. This
article discusses how that can be done with a sample Customer Web API.
In this example you will use a Customer Web API that does CRUD operations on
the Customers table of Northwind database. This Web API is shown below:
public class CustomerController : ApiController
{
NorthwindEntities db = new NorthwindEntities();
public List<Customer> Get()
{
return db.Customers.ToList();
}
public Customer Get(string id)
{
return db.Customers.Find(id);
}
public string Post(Customer obj)
{
db.Customers.Add(obj);
db.SaveChanges();
return "Customer added successfully!";
}
public string Put(string id,Customer obj)
{
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
return "Customer modified successfully!";
}
public string Delete(string id)
{
db.Entry(db.Customers.Find(id)).State =
EntityState.Deleted;
db.SaveChanges();
return "Customer deleted successfully!";
}
}
As you can see CustomerController consists of five methods namely Get(),
Get(id), Post(), Put() and Delete(). These methods deal with the GET, GET, POST,
PUT and DELETE verbs respectively.
To call this Web API from client side script you will create a JavaScript
object - AjaxHelper - that consists of five methods namely SelectAll(),
SelectByID(), Insert(), Update() and Delete(). You will then call t these
methods to invoke the respective Web API action.
The AjaxHelper object is shown below:
function AjaxHelper(baseUrl)
{
this._baseUrl = baseUrl;
var callWebAPI = function (url, verb, data, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function (evt) {
var data = JSON.parse(evt.target.responseText);
callback(data);
}
xhr.onerror = function () {
alert("Error while calling Web API");
}
xhr.open(verb, url);
xhr.setRequestHeader("Content-Type",
"application/json");
if (data==null) {
xhr.send();
}
else {
xhr.send(JSON.stringify(data));
}
}
this.SelectAll = function (callback) {
callWebAPI(this._baseUrl, "GET", null, callback);
}
this.SelectByID = function (id, callback) {
callWebAPI(this._baseUrl + "/" + id, "GET",
null, callback);
}
this.Insert = function (obj, callback) {
callWebAPI(this._baseUrl, "POST", obj, callback);
}
this.Update = function (id, obj, callback) {
callWebAPI(this._baseUrl + "/" + id, "PUT", obj, callback);
}
this.Delete = function (id, callback) {
callWebAPI(this._baseUrl + "/" + id, "DELETE",
null, callback);
}
}
The AjaxHelper object receives base URL of the Web API as its constructor
parameter and stores it in a _baseUrl private variable. Then the code shows a
private helper function - callWebAPI() - that creates and configures a new
instance of XMLHttpRequest object. The callWebAPI() function accepts four
parameters - url, verb, data and callback - and configures five aspects of the
XMLHttpRequest object:
- It wires a success function by handling the load event of the
XMLHttpRequest.
- It wires an error function by handling the error event of the
XMLHttpRequest.
- It opens a URL for a specific HTTP verb using open() method.
- It sets the content-type header to application/json since we will be
using JSON format for the communication.
- It calls the send() method by passing the data parameter.
Notice the onload event handler. It retrieves the data returned by the Web
API using responseText property (which will be in JSON format) and parses it
into JavaScript object. The callback parameter supplies a callback function that
will be invoked with the Web API call succeeded.
Then the code shows a series of functions of the AjaxHelper object. The
SelectAll(), SelectByID(), Insert(), Update() and Delete() methods call the
callWebAPI() function by passing the required URL, HTTP verb, data and callback.
You can now use the AjaxHelper object as shown below:
var ajaxHelper = new AjaxHelper("/api/customer");
var selectAllCallback = function (customers) {
alert(customers.length);
}
var selectByIDCallback = function (customer) {
alert(customer.CompanyName);
}
var actionCallback = function (msg) {
alert(msg);
}
//GET
ajaxHelper.SelectAll(selectAllCallback);
ajaxHelper.SelectByID("ALFKI", selectByIDCallback);
//POST
var obj = {
CustomerID: "ABCDE",
CompanyName: "Company 1",
ContactName: "Contact 1",
Country: "USA"
}
ajaxHelper.Insert(obj, actionCallback);
//PUT
obj.CompanyName = "Company 2";
ajaxHelper.Update("ABCDE", obj, actionCallback);
//DELETE
ajaxHelper.Delete("ABCDE", actionCallback);
As you can see calling a Web API is now a matter of invoking the methods of
AjaxHelper object. The callback functions simply display an alert() that
confirms that the underlying operation was successful.