Create and Consume WCF Restful Service Using jQuery


1. Create and Consume WCF Restful Service

This article will show how to create Representational State Transfer (REST) services in WCF and how to consume REST WCF services in ASP.NET and C# applications using jQuery.

Representational State Transfer (REST)

REST is a protocol for exchanging data over a distributed environment. The main idea of REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to do various operations on that resource.

When we talk about the database as a resource we usually talk in terms of the CRUD operations Create, Retrieve, Update and Delete. Now the philosophy of REST is that for a remote resource all these operations should be possible and they should be possible using simple HTTP protocols.

Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:

  1. GET: Retrieve the required data (representation of data) from the remote resource.
  2. POST: Update the current representation of the data on the remote server.
  3. PUT: Insert new data.
  4. DELETE: Delete the specified data from the remote server.

Now we will learn this REST WCF service by creating an example.

Now open Visual Studio and select "File" -> "New" -> "Project..." then select WCF in the left Side then select WCF Service Application then click "OK".



Image 1.

Now delete the IService.cs and Service.cs files.



Image 2.

Now right-click on the project in the Solution Explorer then select "Add New Item" then select "WCF Service" then name it "EmployeeService".



Image 3.

Now I will create a Data Contract as EmployeeDataContract. Right-click on the project in Solution Explorer then select "Add New Item" then add a .cs file and enter the following code into it.



Image 4.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Runtime.Serialization;  
  6.   
  7. namespace REST_WCF_Service  
  8. {  
  9.     [DataContract]  
  10.     public class EmployeeDataContract  
  11.     {  
  12.         [DataMember]  
  13.         public string EmployeeID { getset; }  
  14.   
  15.         [DataMember]  
  16.         public string Name { getset; }  
  17.   
  18.         [DataMember]  
  19.         public string JoiningDate { getset; }  
  20.   
  21.         [DataMember]  
  22.         public string CompanyName { getset; }  
  23.   
  24.         [DataMember]  
  25.         public string Address { getset; }  
  26.     }  

Now open IEmployeeService.cs to define an interface.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8.   
  9. namespace REST_WCF_Service  
  10. {  
  11.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEmployeeService" in both code and config file together.  
  12.     [ServiceContract]  
  13.     public interface IEmployeeService  
  14.     {  
  15.         [OperationContract]  
  16.         [WebInvoke(Method = "GET",  
  17.         RequestFormat = WebMessageFormat.Json,  
  18.         ResponseFormat = WebMessageFormat.Json,  
  19.         UriTemplate = "/GetAllEmployee/")]  
  20.         List<EmployeeDataContract> GetAllEmployee();  
  21.   
  22.   
  23.         [OperationContract]  
  24.         [WebGet(UriTemplate = "/GetEmployeeDetails/{EmpId}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]  
  25.         EmployeeDataContract GetEmployeeDetails(string EmpId);  
  26.   
  27.         [OperationContract]  
  28.         [WebInvoke(UriTemplate = "/AddNewEmployee", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]  
  29.         bool AddNewEmployee(EmployeeDataContract emp);  
  30.   
  31.         [OperationContract]  
  32.         [WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json)]  
  33.         void UpdateEmployee(EmployeeDataContract contact);  
  34.   
  35.         [OperationContract]  
  36.         [WebInvoke(Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "DeleteEmployee/{EmpId}")]  
  37.         void DeleteEmployee(string EmpId);  
  38.   
  39.     }  

Now Open EmployeeService.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7. using System.Xml.Linq;  
  8.   
  9. namespace REST_WCF_Service  
  10. {  
  11.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "EmployeeService" in code, svc and config file together.  
  12.     // NOTE: In order to launch WCF Test Client for testing this service, please select EmployeeService.svc or EmployeeService.svc.cs at the Solution Explorer and start debugging.  
  13.     public class EmployeeService : IEmployeeService  
  14.     {  
  15.   
  16.         public List<EmployeeDataContract> GetAllEmployee()  
  17.         {  
  18.             List<EmployeeDataContract> empList = new List<EmployeeDataContract>();  
  19.   
  20.             XElement xelement = XElement.Load("H:\\EmployeeData.xml");  
  21.             IEnumerable<XElement> employees = xelement.Elements();  
  22.             foreach (var employee in employees)  
  23.             {  
  24.                 Console.WriteLine(employee.Element("Name").Value);  
  25.                 empList.Add(new EmployeeDataContract  
  26.                 {  
  27.                     EmployeeID = employee.Element("EmployeeID").Value,  
  28.                     Name = employee.Element("Name").Value,  
  29.                     JoiningDate = employee.Element("JoiningDate").Value,  
  30.                     CompanyName = employee.Element("CompanyName").Value,  
  31.                     Address = employee.Element("Address").Value  
  32.                 });  
  33.             }  
  34.             return empList;  
  35.         }  
  36.   
  37.         public EmployeeDataContract GetEmployeeDetails(string EmpId)  
  38.         {  
  39.             EmployeeDataContract emp = new EmployeeDataContract();  
  40.   
  41.             try  
  42.             {  
  43.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  44.   
  45.                 IEnumerable<XElement> employee =  
  46.                     (from result in doc.Descendants("DocumentElement").Descendants("Employees")  
  47.                      where result.Element("EmployeeID").Value == EmpId.ToString()  
  48.                      select result);  
  49.   
  50.                 emp.EmployeeID = employee.ElementAt(0).Element("EmployeeID").Value;  
  51.                 emp.Name = employee.ElementAt(0).Element("Name").Value;  
  52.                 emp.JoiningDate = employee.ElementAt(0).Element("JoiningDate").Value;  
  53.                 emp.CompanyName = employee.ElementAt(0).Element("CompanyName").Value;  
  54.                 emp.Address = employee.ElementAt(0).Element("Address").Value;  
  55.             }  
  56.             catch (Exception ex)  
  57.             {  
  58.                 throw new FaultException<string>  
  59.                         (ex.Message);  
  60.             }  
  61.             return emp;  
  62.         }  
  63.   
  64.         public bool AddNewEmployee(EmployeeDataContract employee)  
  65.         {  
  66.             try  
  67.             {  
  68.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  69.   
  70.                 doc.Element("DocumentElement").Add(  
  71.                         new XElement("Employees",  
  72.                         new XElement("EmployeeID", employee.EmployeeID),  
  73.                         new XElement("Name", employee.Name),  
  74.                         new XElement("JoiningDate", employee.JoiningDate),  
  75.                         new XElement("CompanyName", employee.CompanyName),  
  76.                         new XElement("Address", employee.Address)));  
  77.   
  78.                 doc.Save("H:\\EmployeeData.xml");  
  79.             }  
  80.             catch (Exception ex)  
  81.             {  
  82.                 throw new FaultException<string>  
  83.                         (ex.Message);  
  84.             }  
  85.             return true;  
  86.         }  
  87.   
  88.         public void UpdateEmployee(EmployeeDataContract employee)  
  89.         {  
  90.             try  
  91.             {  
  92.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  93.                 var target = doc  
  94.                      .Element("DocumentElement")  
  95.                      .Elements("Employees")  
  96.                      .Where(e => e.Element("EmployeeID").Value == employee.EmployeeID)  
  97.                      .Single();  
  98.   
  99.                 target.Element("Name").Value = employee.Name;  
  100.                 target.Element("JoiningDate").Value = employee.JoiningDate;  
  101.                 target.Element("CompanyName").Value = employee.CompanyName;  
  102.                 target.Element("Address").Value = employee.Address;  
  103.   
  104.                 doc.Save("H:\\EmployeeData.xml");  
  105.             }  
  106.             catch (Exception ex)  
  107.             {  
  108.                 throw new FaultException<string>  
  109.                         (ex.Message);  
  110.             }  
  111.         }  
  112.   
  113.         public void DeleteEmployee(string EmpId)  
  114.         {  
  115.             try  
  116.             {  
  117.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  118.                 foreach (var result in doc.Descendants("DocumentElement").Descendants("Employees"))  
  119.                 {  
  120.                     if (result.Element("EmployeeID").Value == EmpId.ToString())  
  121.                     {  
  122.                         result.Remove();  
  123.                         break;  
  124.                     }  
  125.                 }  
  126.                 doc.Save("H:\\EmployeeData.xml");  
  127.             }  
  128.             catch (Exception ex)  
  129.             {  
  130.                 throw new FaultException<string>  
  131.                         (ex.Message);  
  132.             }  
  133.         }  
  134.     }  

Now make the the following changes in <system.serviceModel> in your web.config:

  1. <system.serviceModel>  
  2.     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"  
  3.       multipleSiteBindingsEnabled="true" />  
  4.     <services>  
  5.       <service name="REST_WCF_Service.EmployeeService">  
  6.         <endpoint address="" behaviorConfiguration="REST_WCF_Service.EmployeeServiceAspNetAjaxBehavior"  
  7.           binding="webHttpBinding" contract="REST_WCF_Service.IEmployeeService" />  
  8.       </service>  
  9.     </services>  
  10.     <behaviors>  
  11.       <endpointBehaviors>  
  12.         <behavior name="REST_WCF_Service.EmployeeServiceAspNetAjaxBehavior">  
  13.           <webHttp/>  
  14.         </behavior>  
  15.       </endpointBehaviors>  
  16.     </behaviors>  
  17.   </system.serviceModel> 

Now our WCF REST is ready to use so create a client application to consume this REST WCF. Here I will create a new web application and by using jQuery I will consume this REST WCF.

The following is my screen.



Image 5.

The Aspx code is:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ConsumeWCF_REST.aspx.cs" Inherits="Web_ClientApplication.ConsumeWCF_REST" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>  
  9.   
  10.     <script type="text/javascript">  
  11.         $(function () {  
  12.             $('#tbDetails').hide();  
  13.   
  14.             $('#btnGetAllEmployee').click(function () {  
  15.                 $.ajax({  
  16.                     type: "GET",  
  17.                     url: "http://localhost:23610/EmployeeService.svc/GetAllEmployee",  
  18.                     contentType: 'json',  
  19.                     dataType: 'json',  
  20.                     success: function (data) {  
  21.                         $.each(data, function (key, value) {  
  22.                             var jsonData = JSON.stringify(value);  
  23.                             var objData = $.parseJSON(jsonData);  
  24.   
  25.                             var EmployeeID = objData.EmployeeID;  
  26.                             var Name = objData.Name;  
  27.                             var JoiningDate = objData.JoiningDate;  
  28.                             var CompanyName = objData.CompanyName;  
  29.                             var Address = objData.Address;  
  30.                             $('<tr><td>' + EmployeeID + '</td><td>' + Name + '</td><td>' + JoiningDate + '</td><td>' + CompanyName + '</td><td>' + Address + '</td></tr>').appendTo('#tbDetails');  
  31.                         });  
  32.                         $('#tbDetails').show();  
  33.                     },  
  34.                     error: function (xhr) {  
  35.                         alert(xhr.responseText);  
  36.                     }  
  37.                 });  
  38.   
  39.             });  
  40.   
  41.             $('#btnGetEmpDetail').click(function () {  
  42.                 var Emp_ID = $("#txtEmpID").val();  
  43.                 $.ajax({  
  44.                     type: "GET",  
  45.                     url: "http://localhost:23610/EmployeeService.svc/GetEmployeeDetails/" + Emp_ID,  
  46.                     contentType: 'json',  
  47.                     dataType: 'json',  
  48.                     success: function (data) {  
  49.                         var jsonData = JSON.stringify(data);  
  50.                         var objData = $.parseJSON(jsonData);  
  51.                         var EmployeeID = objData.EmployeeID;  
  52.                         var Name = objData.Name;  
  53.                         var JoiningDate = objData.JoiningDate;  
  54.                         var CompanyName = objData.CompanyName;  
  55.                         var Address = objData.Address;  
  56.   
  57.                         $('<tr><td>' + EmployeeID + '</td><td>' + Name + '</td><td>' + JoiningDate + '</td><td>' + CompanyName + '</td><td>' + Address + '</td></tr>').appendTo('#tbDetails');  
  58.                         $('#tbDetails').show();  
  59.                     },  
  60.                     error: function (xhr) {  
  61.                         alert(xhr.responseText);  
  62.                     }  
  63.                 });  
  64.   
  65.             });  
  66.   
  67.             $('#btnAddNewEmployee').click(function () {  
  68.                 var EmployeeData = {  
  69.                     "EmployeeID": $("#txtAddEmpID").val(),  
  70.                     "Name": $("#txtAddEmpName").val(),  
  71.                     "JoiningDate": $("#txtAddEmpJoining").val(),  
  72.                     "CompanyName": $("#txtAddEmpCompany").val(),  
  73.                     "Address": $("#txtAddEmpAddress").val()  
  74.                 };  
  75.                 $.ajax({  
  76.                     type: "POST",  
  77.                     url: "http://localhost:23610/EmployeeService.svc/AddNewEmployee",  
  78.                     data: JSON.stringify(EmployeeData),  
  79.                     contentType: "application/json; charset=utf-8",  
  80.                     dataType: "json",  
  81.                     processData: true,  
  82.                     success: function (data, status, jqXHR) {  
  83.                         alert("success…" + data);  
  84.                     },  
  85.                     error: function (xhr) {  
  86.                         alert(xhr.responseText);  
  87.                     }  
  88.                 });  
  89.   
  90.             });  
  91.   
  92.             $('#btnUpdateEmployee').click(function () {  
  93.   
  94.                 var EmployeeData = {  
  95.                     "EmployeeID": $("#txtAddEmpID").val(),  
  96.                     "Name": $("#txtAddEmpName").val(),  
  97.                     "JoiningDate": $("#txtAddEmpJoining").val(),  
  98.                     "CompanyName": $("#txtAddEmpCompany").val(),  
  99.                     "Address": $("#txtAddEmpAddress").val()  
  100.                 };  
  101.                 $.ajax({  
  102.                     type: "PUT",  
  103.                     url: "http://localhost:23610/EmployeeService.svc/UpdateEmployee",  
  104.                     data: JSON.stringify(EmployeeData),  
  105.                     contentType: "application/json; charset=utf-8",  
  106.                     dataType: "json",  
  107.                     processData: true,  
  108.                     success: function (data, status, jqXHR) {  
  109.                         alert("Employee Updated Successfully.");  
  110.                     },  
  111.                     error: function (xhr) {  
  112.                         alert(xhr.responseText);  
  113.                     }  
  114.                 });  
  115.   
  116.             });  
  117.   
  118.             $('#btnDeleteEmployee').click(function () {  
  119.   
  120.                 var Emp_ID = $("#txtEmpID").val();  
  121.                 $.ajax({  
  122.                     type: "DELETE",  
  123.                     url: "http://localhost:23610/EmployeeService.svc/DeleteEmployee",  
  124.                     contentType: "application/json; charset=utf-8",  
  125.                     data: JSON.stringify(Emp_ID),  
  126.                     dataType: "json",  
  127.                     success: function (data, status, jqXHR) {  
  128.                         alert("Employee Data deleted successfully.");  
  129.                     },  
  130.   
  131.                     error: function (jqXHR, status) {  
  132.                         alert("Error occured in Delete Process");  
  133.                     }  
  134.                 });  
  135.   
  136.             });  
  137.   
  138.         });  
  139.     </script>  
  140.   
  141. </head>  
  142. <body>  
  143.     <form id="form1" runat="server">  
  144.   
  145.         <table cellpadding="5" cellspacing="5" style="border: solid 5px red;" width="98%" align="center">  
  146.             <tr>  
  147.                 <td style="background-color: green; color: yellow; height: 30px; font-size: 16pt; font-family: Georgia; text-align: center;" colspan="2">Consume REST WCF using jQuery</td>  
  148.             </tr>  
  149.             <tr>  
  150.                 <td style="vertical-align: top;">  
  151.                     <table cellpadding="5" cellspacing="5" style="border: solid 2px Green; width: 90%; text-align: center;">  
  152.                         <tr>  
  153.                             <td><b>Employee ID:</b></td>  
  154.                             <td style="text-align: left;">  
  155.                                 <input type="text" id="txtEmpID" />  
  156.                             </td>  
  157.                         </tr>  
  158.                         <tr>  
  159.                             <td></td>  
  160.                             <td style="text-align: left;">  
  161.                                 <input type="button" id="btnGetEmpDetail" value="Get Employee Detail" /></td>  
  162.                         </tr>  
  163.                         <tr>  
  164.                             <td></td>  
  165.                             <td style="text-align: left;">  
  166.                                 <input type="button" id="btnGetAllEmployee" value="Get All Employee" /></td>  
  167.                         </tr>  
  168.                         <tr>  
  169.                             <td></td>  
  170.                             <td style="text-align: left;">  
  171.                                 <input type="button" id="btnDeleteEmployee" value="Delete Employee" /></td>  
  172.                         </tr>  
  173.                     </table>  
  174.                 </td>  
  175.   
  176.                 <td style="vertical-align: top; width: 55%; text-align: center;">  
  177.                     <table cellpadding="2" cellspacing="4" style="border: solid 2px Green;" width="90%" align="center">  
  178.                         <tr>  
  179.                             <td>Employee ID #    
  180.                      
  181.                             </td>  
  182.                             <td style="text-align: left;">  
  183.                                 <input type="text" id="txtAddEmpID" /></td>  
  184.                         </tr>  
  185.                         <tr>  
  186.                             <td>Employee Name #                        
  187.                             </td>  
  188.                             <td style="text-align: left;">  
  189.                                 <input type="text" id="txtAddEmpName" /></td>  
  190.                         </tr>  
  191.                         <tr>  
  192.                             <td>Joining Date #                      
  193.                             </td>  
  194.                             <td style="text-align: left;">  
  195.                                 <input type="text" id="txtAddEmpJoining" /></td>  
  196.                         </tr>  
  197.                         <tr>  
  198.                             <td>Company Name #                      
  199.                             </td>  
  200.                             <td style="text-align: left;">  
  201.                                 <input type="text" id="txtAddEmpCompany" /></td>  
  202.                         </tr>  
  203.                         <tr>  
  204.                             <td>Address #                       
  205.                             </td>  
  206.                             <td style="text-align: left;">  
  207.                                 <input type="text" id="txtAddEmpAddress" /></td>  
  208.                         </tr>  
  209.                         <tr>  
  210.                             <td colspan="2">  
  211.                                 <input type="button" id="btnAddNewEmployee" value="Add New Employee" />  
  212.                                 <input type="button" id="btnUpdateEmployee" value="Update Employee" />  
  213.                             </td>  
  214.                         </tr>  
  215.                     </table>  
  216.                 </td>  
  217.             </tr>  
  218.             <tr>  
  219.                 <td height="30px"></td>  
  220.             </tr>  
  221.             <tr>  
  222.                 <td colspan="2">  
  223.                     <table id="tbDetails" cellpadding="5" cellspacing="5" style="border: solid 5px red;">  
  224.                         <thead style="background-color: skyblue; color: White; font-weight: bold">  
  225.                             <tr style="border: solid 1px #000000">  
  226.                                 <td width="15%">Employee ID</td>  
  227.                                 <td width="15%">Name</td>  
  228.                                 <td width="15%">Joining Date</td>  
  229.                                 <td>Company Name</td>  
  230.                                 <td>Address</td>  
  231.                             </tr>  
  232.                         </thead>  
  233.                         <tbody>  
  234.                         </tbody>  
  235.                     </table>  
  236.                 </td>  
  237.             </tr>  
  238.         </table>  
  239.     </form>  
  240. </body>  
  241. </html> 

The following is my XML:



Image 6.

Up Next
    Ebook Download
    View all
    Learn
    View all