SharePoint Pals
 | Sign In
How to create RESTful service in WCF and consume
by Tarun Kumar Chatterjee 27 Jun 2016
Author
.Net – Technology Specialist
Visits   
Today  :   10     Total  :    2807

In one of my erlier article we have seen about how to create REST WebAPI, here we will be creting the REST service using WCF. Let’s the the detils steps below

Create a WCF Service applicatiuon named as RestFulWCFService

clip_image002[1]

Right click on the solution and add a WCF Service named as EmployeeService

clip_image004[1]

Here is my interface code

 namespace RestFulWCFService
 {
     [ServiceContract()]
     public interface IEmployeeService
     {
         [WebGet(UriTemplate = "Employee", ResponseFormat = WebMessageFormat.Json)]
         [OperationContract]       
         List<Employee> GetAllEmployeeDetails();
 
         [WebGet(UriTemplate = "Employee?id={id}", ResponseFormat = WebMessageFormat.Json)]
         [OperationContract]
         Employee GetEmployee(int Id);
 
         [OperationContract]
         [WebInvoke(Method = "POST", UriTemplate = "EmployeePOST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
         void AddEmployee(string newEmp);
 
         [OperationContract]
         [WebInvoke(Method = "PUT", UriTemplate = "EmployeePUT", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
         void UpdateEmployee(string newEmp);
 
         [WebInvoke(Method = "DELETE", UriTemplate = "Employee/{empId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
         [OperationContract]
         void DeleteEmployee(string empId);
     }
 }
 

Below is my interface implement code

 namespace RestFulWCFService
 {
     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
     public  class EmployeeService : IEmployeeService
     {
         public List<Employee> GetAllEmployeeDetails()
         {
             return new EmployeeDAL().EmployeeList;
         }
         public Employee GetEmployee(int id)
         {
             IEnumerable<Employee> empList = new EmployeeDAL().EmployeeList.Where(x => x.EmpId == id);
 
             if (empList != null)
                 return empList.First<Employee>();
             else
                 return null;
         }
         public void AddEmployee(string newEmp)
         {
             var serializer = new JavaScriptSerializer();
             var serializedResult = serializer.Deserialize<List<Employee>>(newEmp);
             new EmployeeDAL().Add(serializedResult[0]);
         }
         public void UpdateEmployee(string updateEmp)
         {
             var serializer = new JavaScriptSerializer();
             var serializedResult = serializer.Deserialize<List<Employee>>(updateEmp);
             new EmployeeDAL().Update(serializedResult[0]);
         }
         public void DeleteEmployee(string empId)
         {
             new EmployeeDAL().Delete(System.Convert.ToInt32(empId));
         }
     }
 
 

Below is the EmployeeDAL code

 namespace RestFulWCFService
 {
     public class EmployeeDAL
     {
         
         
         private List< Employee> empList = new List < Employee>()
         {
             new Employee() { EmpId = 1, Fname = "Tarun1", Lname = "Chatterjee1", JoinDate=new DateTime(2010,1, 1), Age=30,Salary=100000,Designation="Software Engineer"},
             new Employee() { EmpId = 2, Fname = "Tarun2", Lname = "Chatterjee2", JoinDate=new DateTime(2011,1,1), Age=31,Salary=200000,Designation="Software Engineer"},    
             new Employee() { EmpId = 3, Fname = "Tarun3", Lname = "Chatterjee3", JoinDate=new DateTime(2012,1,1), Age=32,Salary=300000,Designation="Software Engineer"},  
             new Employee() { EmpId = 4, Fname = "Tarun4", Lname = "Chatterjee4", JoinDate=new DateTime(2013, 1,1), Age=33,Salary=400000,Designation="Software Engineer"},
         };
 
         public List< Employee> EmployeeList
         {
             get
             {
                 return empList;
             }
         }
 
 
         public void Update(Employee updEmployee)
         {
             Employee existing = empList.Find(p => p.EmpId == updEmployee.EmpId);
 
             if (existing == null)
                 throw new KeyNotFoundException("Specified Employee cannot be found");
 
             existing.Fname = updEmployee.Fname;
             existing.Lname = updEmployee.Lname;
             existing.Age = updEmployee.Age;
         }
 
         public void Delete(int empid)
         {
             Employee existing = empList.Find(p => p.EmpId == empid);
             empList.Remove(existing);
         }
         public void Add(Employee newEmployee)
         {
             empList.Add(new Employee
             {
                 EmpId = newEmployee.EmpId,
                 Fname = newEmployee.Fname,
                 Lname = newEmployee.Lname,
                 Age = newEmployee.Age,
                 JoinDate = DateTime.Now,
                 Designation = newEmployee.Designation,
                 Salary = newEmployee.Salary
             });
         }
     }
     [Serializable]
     [DataContract]
     public class Employee
     {
         [DataMember]
         public int EmpId { get; set; }
         [DataMember]
         public string Fname { get; set; }
         [DataMember]
         public string Lname { get; set; }
         [DataMember]
         public DateTime JoinDate { get; set; }
         [DataMember]
         public int Age { get; set; }
         [DataMember]
         public int Salary { get; set; }
         [DataMember]
         public string Designation { get; set; }
     }
 
 }
 

Below is my web.config code

 <?xml version="1.0"?>
 <configuration>
   <appSettings>
     <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
   </appSettings>
   <system.web>
     <compilation debug="true" targetFramework="4.5.1" />
     <httpRuntime targetFramework="4.5.1"/>
   </system.web>
   <system.serviceModel>
     <services>
       <service name="RestFulWCFService.EmployeeService">
         <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" contract="RestFulWCFService.IEmployeeService">          
         </endpoint>
         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       </service>
     </services>
     <behaviors>
       <serviceBehaviors>
         <behavior name="Default">
           <serviceMetadata httpGetEnabled="true" />
         </behavior>
         <behavior name="">
           <serviceMetadata httpGetEnabled="true" />
           <serviceDebug includeExceptionDetailInFaults="false" />
         </behavior>
       </serviceBehaviors>
       <endpointBehaviors>
         <behavior name="WebBehavior">
           <webHttp helpEnabled="true" />
         </behavior>
       </endpointBehaviors>
     </behaviors>
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
       multipleSiteBindingsEnabled="false" />
   </system.serviceModel>
   <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>    
     <directoryBrowse enabled="true"/>
   </system.webServer>
 </configuration>
 
 

Right click on the Solution and Create the virtual directory

clip_image006

Now build the solution and run, the output will be looking like

clip_image008[1]

So, our service is ready now. Now we will be seeing how to consume the service from a console application

Create a Console application and add the service reference to it

clip_image009

Add the below piece of code in Program.cs and run

 WebChannelFactory<IEmployeeService> wcf = new WebChannelFactory<IEmployeeService>(new Uri("http://localhost/RestFulWCFService/EmployeeService.svc"));
             IEmployeeService client = wcf.CreateChannel();
                         
             //Load all the Employee from the server and display
             foreach (Employee emp in client.GetAllEmployeeDetails())
             {
                 Console.WriteLine(string.Format("EmpID:{0}, Name:{1} {2}", emp.EmpId, emp.Fname, emp.Lname));
             }
             Console.ReadLine();
 
 

clip_image011

Below is the code to consume the service from web

 function PostEmployee() {            
             var EmpUser = "[{\"Age\":30,\"Designation\":\"Software Engineer\",\"EmpId\":5,\"Fname\":\"Tarun\",\"JoinDate\":\"1/1/1990\",\"Lname\":\"Chatterjee\",\"Salary\":500000}]";
             
             $.ajax({
                 type: "POST",
                 url: serviceUrl + "/EmployeePOST",
                 data: JSON.stringify(EmpUser),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data) {                    
                 },
                 error: function (msg) {
                     JSON.stringify(msg);
                 }
             });
 

Hope this article will help you to understand the basic implementation on WCF REST service and how to consume from Console/Web Application.

Happy Coding

Tarun Kumar Chatterjee

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation