Click here to Skip to main content
15,867,594 members
Articles / Web Development / HTML

Consuming WCF REST Services Using jQuery AJAX Calls

Rate me:
Please Sign up or sign in to vote.
4.93/5 (52 votes)
25 Nov 2010CPOL10 min read 394.4K   10.9K   123   55
This article presents a method to consume cross-domain WCF REST Services using jQuery AJAX calls, with an example.

Introduction

This article presents a method to consume cross-domain WCF REST Services using jQuery AJAX calls, with an example.

Background

Representational State Transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. It was first introduced by Roy Fielding in his PhD thesis "Architectural Styles and the Design of Network-based Software Architectures". You can find tutorials on creating WCF REST Services from here, here, and here. Among these tutorials, I find "RESTful WCF Services with No svc file and No config" presented by Steve Michelotti particularly interesting. It is the simplest way to create a WCF REST Service, and probably any type of Service that I have ever found. Instead of focusing on the creation of WCF REST services, this article will present a method to consume WCF REST Services using jQuery AJAX calls at the web browser side, with an example.

SolutionExplorer.JPG

The attached Visual Studio solution has two projects:

  • The "StudentService" project is a WCF REST Service
  • "StudentServiceTestWeb" is a simple "ASP.NET MVC" project, where I will show how to consume the Service exposed by the "StudentService" project using "jQuery" "AJAX" calls from web browsers.

This Visual Studio solution is developed in Visual Studio 2010, and the jQuery version is "1.4.4". In this article, I will first introduce the WCF REST Service project "StudentService" and then introduce the web project "StudentServiceTestWeb". After that, I will talk about some "cross-domain" issues when consuming WCF REST Services using "jQuery" "AJAX" calls from web browsers.

The WCF REST Service project "StudentService"

The WCF REST Service is implemented in a simple "ASP.NET" web application. The method used to develop the example WCF REST Service is an exact copy of the method introduced by Steve Michelotti. If you take a look at his blog, it will make your understanding of this example much easier.

SolutionExplorerService.JPG

Before going to the WCF REST Service, let us first take a look at the data model used by the Service, which is implemented in the "Models\ModelClasses.cs" file:

C#
using System;
using System.Collections.Generic;
 
namespace StudentService.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public Nullable<int> Score { get; set; }
        public string State { get; set; }
    }
 
    public class Department
    {
        public string SchoolName { get; set; }
        public string DepartmentName { get; set; }
        public List<Student> Students { get; set; }
    }
}

Two related classes "Student" and "Department" are implemented, where the "Department" class holds a reference to a "List" of "Student" objects. With these two classes as the data model, the WCF REST Service is implemented in the "Service.cs" file:

C#
using System.Web;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using StudentService.Models;
using System.ServiceModel;
using System.Collections.Generic;
using System;
 
namespace StudentService
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode
        = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service
    {
        [OperationContract]
        [WebGet(UriTemplate = "Service/GetDepartment")]
        public Department GetDepartment()
        {
            Department department = new Department
            {
                SchoolName = "School of Some Engineering",
                DepartmentName = "Department of Cool Rest WCF",
                Students = new List<Student>()
            };
 
            return department;
        }
 
        [OperationContract]
        [WebGet(UriTemplate = "Service/GetAStudent({id})")]
        public Student GetAStudent(string id)
        {
            Random rd = new Random();
            Student aStudent = new Student
                {
                    ID = System.Convert.ToInt16(id), 
                    Name = "Name No. " + id,
                    Score = Convert.ToInt16(60 + rd.NextDouble() * 40),
                    State = "GA"
                };
 
            return aStudent;
        }
 
        [OperationContract]
        [WebInvoke(Method ="POST", 
         UriTemplate = "Service/AddStudentToDepartment",
         BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public Department
            AddStudentToDepartment(Department department, Student student)
        {
            List<Student> Students = department.Students;
            Students.Add(student);
 
            return department;
        }
    }
}

Three "OperationContracts" are implemented in this Service:

  • "GetDepartment" accepts a "GET" method. It takes no input parameter, and returns a "Department" object. This "Department" object has an empty "Students" "List".
  • "GetAStudent" accepts a "GET" method. It takes a single input parameter "id". It creates a "Student" object of the same "id", and returns this object to the caller.
  • "AddStudentToDepartment" accepts a "POST" method; it takes two input parameters, a "Department" object and a "Student" object. It then adds the "Student" to the "Students" "List" of the "Department", and returns the "Department" object back to the caller.

To make this WCF REST Service work, we will need to make changes to the "Global.asax.cs" file and the "Web.config" file. We will need to add the following code to the "Application_Start" event in "Global.asax.cs":

C#
protected void Application_Start(object sender, EventArgs e)
{
     RouteTable.Routes.Add(new ServiceRoute("", 
          new WebServiceHostFactory(), 
          typeof(Service)));
}

We will also need to add the following configuration into the "Web.config" file:

XML
 <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true"
          automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
    </standardEndpoints>
</system.serviceModel>

For those of you who are familiar with WCF Service development, you may be surprised by the simplicity to develop and configure a WCF REST Service. Yes, without an "svc" file and without the "Endpoint" configuration, the WCF REST Service is completed and works. The following picture shows the "help page" of this WCF REST Service:

ServiceHelp.JPG

The "Description" field has the "URL" to access each OperationContract's method in the development environment in Debug mode.

The MVC web project "StudentServiceTestWeb"

To demonstrate how to consume the WCF REST Service using "jQuery" "AJAX" calls, an "ASP.NET MVC" application is developed.

SolutionExplorerWeb.JPG

This web application is the simplest "MVC" application possible. It has only one "controller" in the "Controllers\HomeController.cs" file:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace StudentServiceTestWeb.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

The only purpose of the "HomeController" is to load the web application's only "View" page "Index.aspx":

ASP.NET
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Consume WCF Rest Service with jQuery</title>
    <link rel="stylesheet"
        href='<%= Url.Content("~/Content/Styles/Site.css") %>'
        type="text/css" />
</head>
<body>
    <div id="divContainer">
    <div id="divDepartmentHeader"></div>
    <div id="divStudentList"></div>
    <div id="divNewStudent">
        <span>Pending new student: - Click "Add student to department" button</span>
        <br />
        <span id="spanStudentList"></span>
    </div>
 
    <div id="divButtonContainer" style="float: right; margin: 2px">
        <button id="btnAquireNewStudent">Aquire a new student</button>
        <button id="btnAddStudentToDepartment">
            Add student to department</button>
    </div>
    </div>
</body>
</html>
 
<script src='<%= Url.Content("~/Content/Scripts/jquery-1.4.4.min.js") %>'
        type="text/javascript">
</script>
 
<script type="text/javascript">
    // Urls to access the WCF Rest service methods
    var GetDepartmentURl = "http://localhost:4305/Service/GetDepartment";
    var GetAStudent = "http://localhost:4305/Service/GetAStudent";
    var AddStudentToDepartment = "http://localhost:4305/Service/AddStudentToDepartment";
 
    var nextStudentID = 1;
    var jDepartment = null;
    var jPendingStudent = null;
 
    // Utility function - Create HTML table on Json data
    function makeTable(jObject) {
        var jArrayObject = jObject
        if (jObject.constructor != Array) {
            jArrayObject = new Array();
            jArrayObject[0] = jObject;
        }
 
        var table = document.createElement("table");
        table.setAttribute('cellpadding', '4px');
        table.setAttribute('rules', 'all');
        var tboby = document.createElement("tbody");
 
        var trh = document.createElement('tr');
        for (var key in jArrayObject[0]) {
            var th = document.createElement('th');
            th.appendChild(document.createTextNode(key));
            trh.appendChild(th);
        }
        tboby.appendChild(trh);
 
        $.each(jArrayObject, function (i, v) {
            var tr = document.createElement('tr');
            for (var key in v) {
                var td = document.createElement('td');
                td.appendChild(document.createTextNode(v[key]));
                tr.appendChild(td);
            }
            tboby.appendChild(tr);
        });
        
        table.appendChild(tboby)
 
        return table;
    }
 
    $(document).ready(function () {
        $.ajax({
            cache: false,
            type: "GET",
            async: false,
            dataType: "json",
            url: GetDepartmentURl,
            success: function (department) {
                jDepartment = department;
 
                var div = document.createElement("div");
                var span = document.createElement("span");
                span.setAttribute('id', 'DepartmentHeader');
                span.appendChild(document.createTextNode(department.SchoolName));
                span.appendChild(document.createTextNode(" - "));
                span.appendChild(document.createTextNode(department.DepartmentName));
                div.appendChild(span);
                span = document.createElement("span");
                div.appendChild(document.createElement("br"));
                span.appendChild(document.createTextNode("List of students:"));
                div.appendChild(span);
 
                $("#divDepartmentHeader").html("").append(div);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
 
        $("#btnAquireNewStudent").click(function () {
            if (jPendingStudent != null) {
                alert("Please add the pending student to the department first");
                return;
            }
 
            $.ajax({
                cache: false,
                type: "GET",
                async: false,
                url: GetAStudent + "(" + nextStudentID + ")",
                dataType: "json",
                success: function (student) {
                    jPendingStudent = student;
                    nextStudentID++;
 
                    var table = makeTable(student);
                    $("#spanStudentList").html("").append(table);
                    $("#divNewStudent").css("visibility", "visible");
                    $("#divNewStudent").show();
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });
 
        $("#btnAddStudentToDepartment").click(function () {
            if (jDepartment == null) {
                alert("Please wait until the department loads");
                return;
            }
            if (jPendingStudent == null) {
                alert("Please first get a new student to add to the department");
                return;
            }
 
            var jData = {};
            jData.department = jDepartment;
            jData.student = jPendingStudent;
 
            $.ajax({
                cache: false,
                type: "POST",
                async: false,
                url: AddStudentToDepartment,
                data: JSON.stringify(jData),
                contentType: "application/json",
                dataType: "json",
                success: function (department) {
                    jPendingStudent = null;
                    jDepartment = department;
 
                    var table = makeTable(department.Students);
                    $("#divStudentList").html("").append(table);
                    $("#divNewStudent").hide();
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });
    });
</script>

All the client-side "JavaScript" code to access the WCF REST Service using "jQuery" "AJAX" calls is implemented in the "Index.aspx" page. Before going to the "JavaScript" section, let us first take a look at the HTML components:

  • There are a couple of "<div>" tags in the "<body>" tag. These "<div>" tags will be used as place holders by the "JavaScript" code to build the application's UI components.
  • A "button" control "btnAquireNewStudent". Clicking on this button will issue an "AJAX" call to the OperationContract's "GetAStudent".
  • A "button" control "btnAddStudentToDepartment". Clicking on this button will issue an "AJAX" call to the OperationContract's "AddStudentToDepartment".

The "JavaScript" code in the "Index.aspx" page is pretty simple:

  • In the "$(document).ready()" event, an "AJAX" call is made to the "GetDepartment" method in the WCF REST Service. Upon receiving the response from the server, the UI is updated by the information from the "JSON" representation of the "Department" object. This "JSON" object is then assigned to the global variable "jDepartment".
  • In the click event of "btnAquireNewStudent", an "AJAX" call is made to the "GetAStudent" method. The global variable "nextStudentID" is used as the input parameter. If the call is successful, the function "makeTable" is used to create an HTML "table" using the received "JSON" object, and the UI is updated to show the newly received student. This "JSON" object is then assigned to the global variable "jPendingStudent", and the global variable "nextStudentID" is adjusted, so a different "id" is sent when the user clicks this "button" again.
  • In the click event of "btnAddStudentToDepartment", an "AJAX" call is made to the "AddStudentToDepartment" method. This call uses a "POST" method. The data posted to "AddStudentToDepartment" is a "JSON" string, which is generated by wrapping the "JSON" objects jDepartment and jPendingStudent. If the call is successful, the function "makeTable" is called to generate an HTML "table" for the "List" of the "Student" objects, and the UI is updated accordingly.

Now we have finished this "simple" "StudentServiceTestWeb" project. But before we can test run it in the development environment, we have another issue to talk about.

The "cross-domain" issue

The "Cross-domain" or "Cross-site" HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. Generally speaking, the default behavior of web browsers is to block "cross-domain" accesses if they feel that the types of accesses are "un-safe". From the web browser's perspective, a domain is recognized by the "URL". For example, when the browser loads an image from "http://domainb.foo:8080/image.jpg", the domain of the image file is identified by "http://domainb.foo:8080", which includes the "port number".

In this article, Visual Studio assigns the port number "4305" to the WCF REST Service and the port number "5187" to the web application to the debug servers to run the application. When an "AJAX" call is made to the WCF REST Service from the web application in Debug mode, it is considered "cross-domain" by the web browsers, since the web application and the Service have different "port numbers". To address this problem, we will need the WCF REST Service to explicitly tell the web browsers that "cross-domain" access is allowed. This can be done in the "Global.asax.cs" file in the "StudentService" project:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.ServiceModel.Activation;
using System.Web.Routing;
 
namespace StudentService
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.Add(new ServiceRoute("", 
                       new WebServiceHostFactory(), typeof(Service)));
        }
 
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
 
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.Cache.SetNoStore();
                
                EnableCrossDmainAjaxCall();
        }
 
        private void EnableCrossDmainAjaxCall()
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
                          "http://localhost:5187");
 
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", 
                              "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                              "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
                              "1728000");
                HttpContext.Current.Response.End();
            }
        }
    }
}

In the "Application_BeginRequest" event, the function "EnableCrossDmainAjaxCall" is called. This function sends the required "HTTP access control" headers to the browsers. Among the popular browsers like "Firefox", "Chrome", "Safari", and "IE", each may behave slightly differently, but generally, all follow a similar pattern.

  • For the "jQuery" "AJAX" calls to be successful, browsers must receive the response header "Access-Control-Allow-Origin", and the value of this header must identify the domain of the calling web application. If you want all the web pages from all the domains to access your services, you can set the value as "*".
  • If the browsers feel that your "AJAX" call is "un-safe", they will send a "preflighted" request to the server before they make the actual "AJAX" call. In this article, the call to the "OperationContract" "AddStudentToDepartment" uses a "POST" method, and the "content type" is "application/json", it is considered as "un-safe" by most browsers. The "preflighted" request uses the "OPTIONS" method. If the server receives an "OPTIONS" request, it needs to use "Access-Control-Allow-Methods" to inform the browser the HTTP methods allowed for the "AJAX" call. It also needs to use "Access-Control-Allow-Headers" to inform the browser the HTTP headers allowed in the actual "AJAX" call. In this article, the WCF REST Service allows the browsers to use "POST" and "GET" methods, and allows the headers "Content-Type" and "Accept" used in the "AJAX" call.
  • The value of the "Access-Control-Max-Age" tells the browsers how long the "preflighted" results remain valid, so when the browsers issue the same "AJAX" call again, they do not need to send the "OPTIONS" request before the "preflighted" results expire.

Different browsers may be slightly different with the "HTTP access control". But I have tested the "EnableCrossDmainAjaxCall" function with "Firefox", "Chrome", "Safari", and "IE". They all respond nicely to the headers sent by the "EnableCrossDmainAjaxCall" function.

Run the application

To run the application, you need to make sure that both the WCF REST Service and the web application are running. If you set the "StudentServiceTestWeb" project as the "start up" project, when you debug run the application, Visual Studio should start both the Service and the web application. When the web page first launches, the "OperationContract" "GetDepartment" is called and the school name and the department name are loaded from the Service as shown on the web browser:

ApplicationLaunch.JPG

Click on the "Acquire a new student" button; the "OperationContract" "GetAStudent" is called and the information for the new "Student" is displayed in the web browser:

ApplicationNewStudent.JPG

Click on the "Add student to department" button; the "OperationContract" "AddStudentToDepartment" is called and the UI is updated to show the "List" of "Student" objects in the "Department". The following pictures show the result after multiple "Student" objects are added to the "Department":

ApplicationAddStudent.JPG

Points of Interest

  • This article presents a method to consume cross-domain WCF REST Services using jQuery AJAX calls with an example.
  • Using the method from Steve Michelotti's blog, a WCF REST Service can be easily implemented.
  • To call a WCF REST Service located at a different domain other than your web application, you need to be aware of the "HTTP access control" issue. I have tested the method presented in this article, and it works on all the popular browsers.
  • When I developed the function "EnableCrossDmainAjaxCall" used in this article, I put a lot of effort to "allow" "cross-domain" "AJAX" calls. By studying the materials in the "HTTP access control" link, it should not be difficult to create a mechanism to "allow" the wanted "cross-domain" accesses and "block" all others for better security.
  • Instead of using the method presented in this article, there are some discussions on using "JsonP" to solve "cross-domain" issues. If you are interested, you can take a look at it.
  • An interesting thing that I noticed during my own test is that the web application runs very fast in "IE" but significantly slower in other browsers when the WCF REST Service is hosted in the Visual Studio debug server. I then deployed both the web application and the Service in true IIS servers. When they are hosted by true IIS servers, there is no speed difference among the browsers, at least no human noticeable speed difference.
  • I hope you like my postings, and I hope that they can help you one way or the other.

History

This is the first revision of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions

 
QuestionEndpoint Not Found Pin
Zek Patafta26-Feb-15 2:10
Zek Patafta26-Feb-15 2:10 
QuestionWCF publish Pin
woot_woot31-Dec-14 14:54
woot_woot31-Dec-14 14:54 
GeneralMy vote of 5 Pin
bhalaniabhishek8-Aug-14 3:48
bhalaniabhishek8-Aug-14 3:48 
GeneralMy vote of 5 Pin
bhalaniabhishek15-Jul-14 20:04
bhalaniabhishek15-Jul-14 20:04 
QuestionReg Student Service Project and How to add additional class Pin
Palanivelrajan28-Apr-14 19:50
Palanivelrajan28-Apr-14 19:50 
AnswerRe: Reg Student Service Project and How to add additional class Pin
Dr. Song Li29-Apr-14 3:03
Dr. Song Li29-Apr-14 3:03 
QuestionResponse is not available in this context. Pin
Member 103179135-Oct-13 18:32
Member 103179135-Oct-13 18:32 
QuestionSharepoint 2013 Pin
Narkohn18-Jul-13 1:12
Narkohn18-Jul-13 1:12 
GeneralMy vote of 5 Pin
pravesh.alex14-Jun-13 9:41
pravesh.alex14-Jun-13 9:41 
GeneralMy vote of 5 Pin
Prasad Khandekar11-Jun-13 3:37
professionalPrasad Khandekar11-Jun-13 3:37 
QuestionPlease help me to secure Rest WebService (+5) Pin
toregua16-May-13 2:56
toregua16-May-13 2:56 
QuestionAll Good except keep the login info in server Session Pin
coolioo8-May-13 21:49
coolioo8-May-13 21:49 
GeneralMy vote of 5 Pin
sanjay198825-Apr-13 3:35
sanjay198825-Apr-13 3:35 
GeneralMy vote of 5 Pin
jujiro19-Feb-13 5:51
jujiro19-Feb-13 5:51 
GeneralMy vote of 5 Pin
Ankkster11-Jan-13 7:28
Ankkster11-Jan-13 7:28 
GeneralMy vote of 5 Pin
pgtreinis21-Dec-12 14:02
pgtreinis21-Dec-12 14:02 
GeneralRe: My vote of 5 Pin
Dr. Song Li21-Dec-12 15:59
Dr. Song Li21-Dec-12 15:59 
QuestionThank you Sooo Much Pin
0740523-Nov-12 20:36
0740523-Nov-12 20:36 
AnswerRe: Thank you Sooo Much Pin
Dr. Song Li24-Nov-12 3:47
Dr. Song Li24-Nov-12 3:47 
QuestionEnable cross-site HTTP request for self-hosted RESTful wcf service Pin
vnngoc15619-Sep-12 19:45
vnngoc15619-Sep-12 19:45 
AnswerRe: Enable cross-site HTTP request for self-hosted RESTful wcf service Pin
Dr. Song Li20-Sep-12 3:31
Dr. Song Li20-Sep-12 3:31 
Hi Ngoc,

I normally do not do self-hosting, because IIS (or other web servers) is not expensive and comes with a lot of features that can help me to manage the other aspects of the service or web application.

Thank you,
Song
QuestionWcf rest Srvice Pin
srinivasGT17-Aug-12 0:08
srinivasGT17-Aug-12 0:08 
AnswerRe: Wcf rest Srvice Pin
Dr. Song Li17-Aug-12 3:59
Dr. Song Li17-Aug-12 3:59 
GeneralMy vote of 5 Pin
dorosh13-Jul-12 11:11
dorosh13-Jul-12 11:11 
GeneralMy vote of 5 Pin
Justin Cooney4-Jul-12 5:02
Justin Cooney4-Jul-12 5:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.