Create and Consume WCF Restful Service

Representational State Transfer (REST) is a protocol for exchanging data over a distributed environment. The fundamental 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 Create, Retrieve, Update and Delete (CRUD) operations. 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:

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

Now we will learn this REST WCF service with an example.

Here in this example I will show a REST WCF Service by taking an Employee 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 and provide the the name "EmployeeService".



Image 3.

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



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 the 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.   
  16. [OperationContract]  
  17.         [WebGet(UriTemplate = "/GetEmployeeDetails/{EmpId}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]  
  18.         EmployeeDataContract GetEmployeeDetails(string EmpId);  
  19.   
  20.         [OperationContract]  
  21.         [WebInvoke(UriTemplate = "/AddNewEmployee", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]  
  22.         bool AddNewEmployee(EmployeeDataContract emp);  
  23.   
  24.         [OperationContract]  
  25.         [WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json)]  
  26.         void UpdateEmployee(EmployeeDataContract contact);  
  27.   
  28.         [OperationContract]  
  29.         [WebInvoke(Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "DeleteEmployee/{EmpId}")]  
  30.         void DeleteEmployee(string EmpId);  
  31.     }  

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.         public EmployeeDataContract GetEmployeeDetails(string EmpId)  
  16.         {  
  17.             EmployeeDataContract emp = new EmployeeDataContract();  
  18.   
  19.             try  
  20.             {  
  21.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  22.   
  23.                 IEnumerable<XElement> employee =  
  24.                     (from result in doc.Descendants("DocumentElement").Descendants("Employees")  
  25.                      where result.Element("EmployeeID").Value == EmpId.ToString()  
  26.                      select result);  
  27.   
  28.                 emp.EmployeeID = employee.ElementAt(0).Element("EmployeeID").Value;  
  29.                 emp.Name = employee.ElementAt(0).Element("Name").Value;  
  30.                 emp.JoiningDate = employee.ElementAt(0).Element("JoiningDate").Value;  
  31.                 emp.CompanyName = employee.ElementAt(0).Element("CompanyName").Value;  
  32.                 emp.Address = employee.ElementAt(0).Element("Address").Value;  
  33.             }  
  34.             catch (Exception ex)  
  35.             {  
  36.                 throw new FaultException<string>  
  37.                         (ex.Message);  
  38.             }  
  39.             return emp;  
  40.         }  
  41.   
  42.         public bool AddNewEmployee(EmployeeDataContract employee)  
  43.         {  
  44.             try  
  45.             {  
  46.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  47.   
  48.                 doc.Element("DocumentElement").Add(  
  49.                         new XElement("Employees",  
  50.                         new XElement("EmployeeID", employee.EmployeeID),  
  51.                         new XElement("Name", employee.Name),  
  52.                         new XElement("JoiningDate", employee.JoiningDate),  
  53.                         new XElement("CompanyName", employee.CompanyName),  
  54.                         new XElement("Address", employee.Address)));  
  55.   
  56.                 doc.Save("H:\\EmployeeData.xml");  
  57.             }  
  58.             catch (Exception ex)  
  59.             {  
  60.                 throw new FaultException<string>  
  61.                         (ex.Message);  
  62.             }  
  63.             return true;  
  64.         }  
  65.   
  66.         public void UpdateEmployee (EmployeeDataContract employee)  
  67.         {  
  68.             try  
  69.             {  
  70.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  71.                 var target = doc  
  72.                      .Element("DocumentElement")  
  73.                      .Elements("Employees")  
  74.                      .Where(e => e.Element("EmployeeID").Value == employee.EmployeeID)  
  75.                      .Single();  
  76.   
  77.                 target.Element("Name").Value = employee.Name;  
  78.                 target.Element("JoiningDate").Value = employee.JoiningDate;  
  79.                 target.Element("CompanyName").Value = employee.CompanyName;  
  80.                 target.Element("Address").Value = employee.Address;  
  81.   
  82.                 doc.Save("H:\\EmployeeData.xml");  
  83.             }  
  84.             catch (Exception ex)  
  85.             {  
  86.                 throw new FaultException<string>  
  87.                         (ex.Message);  
  88.             }  
  89.         }  
  90.   
  91.         public void DeleteEmployee(string EmpId)  
  92.         {  
  93.             try  
  94.             {  
  95.                 XDocument doc = XDocument.Load("H:\\EmployeeData.xml");  
  96.                 foreach (var result in doc.Descendants("DocumentElement").Descendants("Employees"))  
  97.                 {  
  98.                     if (result.Element("EmployeeID").Value == EmpId.ToString())  
  99.                     {  
  100.                         result.Remove();  
  101.                         break;  
  102.                     }  
  103.                 }  
  104.                 doc.Save("H:\\EmployeeData.xml");  
  105.             }  
  106.             catch (Exception ex)  
  107.             {  
  108.                 throw new FaultException<string>  
  109.                         (ex.Message);  
  110.             }  
  111.         }  
  112.     }  

Now create a new project (WindowForm) to consume this REST WCF service. Here I will use a WPF application.

  1. <Window x:Class="WpfApplication1.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         Title="Consume WCF REST To Perform CRUD Operations" Height="471" Width="625">  
  5.     <Grid Margin="0,0,-67,-31">  
  6.         <Grid.ColumnDefinitions>  
  7.             <ColumnDefinition/>  
  8.             <ColumnDefinition Width="37*"/>  
  9.         </Grid.ColumnDefinitions>  
  10.         <Label Content="Employee Id" HorizontalAlignment="Left" Margin="36,36,0,0" VerticalAlignment="Top" Width="120" Grid.Column="1"/>  
  11.         <TextBox HorizontalAlignment="Left" Height="23" Margin="187,36,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.Column="1" Name="txtEmpId"/>  
  12.         <Button Content="Click To View Employee Detail" HorizontalAlignment="Left" Margin="329,36,0,0" VerticalAlignment="Top" Width="194" Grid.Column="1" Click="btn_ViewEmployeeDetail"/>  
  13.         <Label Content="Employee ID" HorizontalAlignment="Left" Margin="35.632,87,0,0" VerticalAlignment="Top" Grid.Column="1"/>  
  14.         <Label Content="Name" HorizontalAlignment="Left" Margin="35.632,135,0,0" VerticalAlignment="Top" Grid.Column="1"/>  
  15.         <Label Content="Joining Date" HorizontalAlignment="Left" Margin="35.632,191,0,0" VerticalAlignment="Top" Grid.Column="1"/>  
  16.         <Label Content="Company Name" HorizontalAlignment="Left" Margin="35.632,239,0,0" VerticalAlignment="Top" Grid.Column="1"/>  
  17.         <Label Content="Address" HorizontalAlignment="Left" Margin="35.632,290,0,0" VerticalAlignment="Top" Grid.Column="1"/>  
  18.         <TextBox HorizontalAlignment="Left" Height="23" Margin="187,87,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120" Grid.Column="1" Name="txtShowEmpId"/>  
  19.         <TextBox HorizontalAlignment="Left" Height="23" Margin="187,135,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1" Name="txtShowEmpName"/>  
  20.         <TextBox HorizontalAlignment="Left" Height="23" Margin="187,195,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1" Name="txtShowEmpJoiningDate"/>  
  21.         <TextBox HorizontalAlignment="Left" Height="23" Margin="187,243,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1" Name="txtShowCompany"/>  
  22.         <TextBox HorizontalAlignment="Left" Height="44" Margin="187,290,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1" Name="txtShowAddress"/>  
  23.         <Button Content="Add New Employee" Grid.Column="1" HorizontalAlignment="Left" Margin="50,379,0,0" VerticalAlignment="Top" Width="120" Height="48" Click="btn_AddnewEmployee"/>  
  24.         <Button Content="Update Employee" Grid.Column="1" HorizontalAlignment="Left" Margin="205,379,0,0" VerticalAlignment="Top" Width="120" Height="48" Click="btn_UpdateEmployee"/>  
  25.         <Button Content="Delete Employee" Grid.Column="1" HorizontalAlignment="Left" Margin="361,379,0,0" VerticalAlignment="Top" Width="120" Height="48" Click="btn_DeleteEmployee"/>  
  26.   
  27.     </Grid>  
  28. </Window> 

Run the application and do a CRUD operation by consuming REST WCF.



Image 5.

Code to perform the preceding operations is:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Windows;  
  7. using System.Windows.Controls;  
  8. using System.Windows.Data;  
  9. using System.Windows.Documents;  
  10. using System.Windows.Input;  
  11. using System.Windows.Media;  
  12. using System.Windows.Media.Imaging;  
  13. using System.Windows.Navigation;  
  14. using System.Windows.Shapes;  
  15. using System.Runtime.Serialization;  
  16. using System.Runtime.Serialization.Json;  
  17. using System.Net;  
  18. using System.IO;  
  19. using REST_WCF_Service;  
  20.   
  21. namespace WPF_ClientApplication  
  22. {  
  23.     /// <summary>  
  24.     /// Interaction logic for MainWindow.xaml  
  25.     /// </summary>  
  26.     public partial class MainWindow : Window  
  27.     {  
  28.         public MainWindow()  
  29.         {  
  30.             InitializeComponent();  
  31.         }  
  32.   
  33.         private void btn_AddnewEmployee(object sender, RoutedEventArgs e)  
  34.         {  
  35.             EmployeeDataContract employee = new EmployeeDataContract  
  36.             {  
  37.                 EmployeeID = txtShowEmpId.Text,  
  38.                 Name = txtShowEmpName.Text,  
  39.                 JoiningDate = txtShowEmpJoiningDate.Text,  
  40.                 CompanyName = txtShowCompany.Text,  
  41.                 Address = txtShowAddress.Text  
  42.             };  
  43.   
  44.             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(EmployeeDataContract));  
  45.             MemoryStream mem = new MemoryStream();  
  46.             ser.WriteObject(mem, employee);  
  47.             string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);  
  48.             WebClient webClient = new WebClient();  
  49.             webClient.Headers["Content-type"] = "application/json";  
  50.             webClient.Encoding = Encoding.UTF8;  
  51.             webClient.UploadString("http://localhost:23610/EmployeeService.svc/AddNewEmployee", "POST", data);  
  52.             MessageBox.Show("Employee Saved Successfully...");  
  53.   
  54.             txtShowEmpId.Text = "";  
  55.             txtShowEmpName.Text = "";  
  56.             txtShowEmpJoiningDate.Text = "";  
  57.             txtShowCompany.Text = "";  
  58.             txtShowAddress.Text = "";  
  59.         }  
  60.   
  61.         private void btn_ViewEmployeeDetail(object sender, RoutedEventArgs e)  
  62.         {  
  63.             WebClient proxy = new WebClient();  
  64.             string serviceURL = string.Format("http://localhost:23610/EmployeeService.svc/GetEmployeeDetails/{0}", txtEmpId.Text);  
  65.             byte[] data = proxy.DownloadData(serviceURL);  
  66.             Stream stream = new MemoryStream(data);  
  67.             DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(EmployeeDataContract));  
  68.             EmployeeDataContract employee = obj.ReadObject(stream) as EmployeeDataContract;  
  69.             txtShowEmpId.Text = employee.EmployeeID;  
  70.             txtShowEmpName.Text = employee.Name;  
  71.             txtShowEmpJoiningDate.Text = employee.JoiningDate;  
  72.             txtShowCompany.Text = employee.CompanyName;  
  73.             txtShowAddress.Text = employee.Address;  
  74.         }  
  75.   
  76.         private void btn_UpdateEmployee(object sender, RoutedEventArgs e)  
  77.         {  
  78.             EmployeeDataContract employeeContact = new EmployeeDataContract  
  79.             {  
  80.                 EmployeeID = txtShowEmpId.Text,  
  81.                 Name = txtShowEmpName.Text,  
  82.                 JoiningDate = txtShowEmpJoiningDate.Text,  
  83.                 CompanyName = txtShowCompany.Text,  
  84.                 Address = txtShowAddress.Text  
  85.             };  
  86.   
  87.             WebClient client = new WebClient();  
  88.             client.Headers["Content-type"] = "application/json";  
  89.   
  90.             MemoryStream ms = new MemoryStream();  
  91.             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(EmployeeDataContract));  
  92.             ser.WriteObject(ms, employeeContact);  
  93.   
  94.             // invoke the REST method  
  95.             client.UploadData("http://localhost:23610/EmployeeService.svc/UpdateEmployee", "PUT", ms.ToArray());  
  96.   
  97.             MessageBox.Show("Employee updated Successfully...");  
  98.   
  99.             txtShowEmpId.Text = "";  
  100.             txtShowEmpName.Text = "";  
  101.             txtShowEmpJoiningDate.Text = "";  
  102.             txtShowCompany.Text = "";  
  103.             txtShowAddress.Text = "";  
  104.   
  105.         }  
  106.   
  107.         private void btn_DeleteEmployee(object sender, RoutedEventArgs e)  
  108.         {  
  109.             WebClient client = new WebClient();  
  110.             client.Headers["Content-type"] = "application/json";  
  111.   
  112.             MemoryStream ms = new MemoryStream();  
  113.             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(string));  
  114.             ser.WriteObject(ms, txtEmpId.Text);  
  115.   
  116.             // invoke the REST method  
  117.             byte[] data = client.UploadData("http://localhost:23610/EmployeeService.svc/DeleteEmployee", "DELETE", ms.ToArray());  
  118.   
  119.             MessageBox.Show("Employee deleted Successfully...");  
  120.   
  121.             txtShowEmpId.Text = "";  
  122.             txtShowEmpName.Text = "";  
  123.             txtShowEmpJoiningDate.Text = "";  
  124.             txtShowCompany.Text = "";  
  125.             txtShowAddress.Text = "";  
  126.         }  
  127.     }  

The following is my XML:



Image 6.

Up Next
    Ebook Download
    View all
    Learn
    View all