How to create RESTful service in WCF and consume

Tarun Kumar Chatterjee
.Net – Technology Specialist
Published On :   27 Jun 2016
Visit Count
Today :  4    Total :   3452
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!

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

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.

KWizCom Scan