SharePoint Pals
 | Sign In
How to create RESTful service in WCF and consume
by Tarun Kumar Chatterjee 27 Jun 2016
.Net – Technology Specialist
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


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


Here is my interface code

 namespace RestFulWCFService
     public interface IEmployeeService
         [WebGet(UriTemplate = "Employee", ResponseFormat = WebMessageFormat.Json)]
         List<Employee> GetAllEmployeeDetails();
         [WebGet(UriTemplate = "Employee?id={id}", ResponseFormat = WebMessageFormat.Json)]
         Employee GetEmployee(int Id);
         [WebInvoke(Method = "POST", UriTemplate = "EmployeePOST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
         void AddEmployee(string newEmp);
         [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)]
         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>();
                 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
                 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);
         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
     public class Employee
         public int EmpId { get; set; }
         public string Fname { get; set; }
         public string Lname { get; set; }
         public DateTime JoinDate { get; set; }
         public int Age { get; set; }
         public int Salary { get; set; }
         public string Designation { get; set; }

Below is my web.config code

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

Right click on the Solution and Create the virtual directory


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


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


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));


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}]";
                 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) {

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

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


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 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

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services

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