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
{
[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
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));
}
Console.ReadLine();
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
Leave a comment