Tag Archives: crud operations using wcf restful service

CRUD Operations using WCF Rest API

This Tutorial will explain how to implement crud operations using WCF Rest API.

Open Visual Studio 2012. Go to create new project tab. Select “WCF Service Application” from WCF templates and name it WCFCrudService.
using WCF Rest API Crud operation are performed by

GET – To Get data from database
POST – To Insert data into database
PUT – To Update data into database
DELETE – To delete data in database

Create a model class and name it Employee in the project. And write the below code in the file.

[DataContract]
public class Employee
{
    [DataMember]
    public string EmployeeID { get; set; }
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public string DOB { get; set; }
    [DataMember]
    public string Gender { get; set; }
    [DataMember]
    public string Nationality { get; set; }
    [DataMember]
    public string Language { get; set; }
    [DataMember]
    public string Address { get; set; }
}


Now the most important part of wcf rest api is how the rest api will be exposed to the clients. Like WCF service WCF Rest API will be exposed via interface. We are using WebGet attribute which represent that a service operation is a retrieval operation and WebInvoke attribute represent that a service operation is an invoke operation.

Rename IService1.cs file name with ICrudService.cs. And write the below code in the file.

[ServiceContract]
public interface ICrudService
{
    [OperationContract]
    [WebGet(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json,UriTemplate="Employees")]
    List<Employee> GetAllEmployees();

    [OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Employee/{id}")]
    Employee GetEmployee(string id);

    [OperationContract]
    [WebInvoke(Method="POST",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "AddEmployee")]
    bool AddEmployee(Employee employeeData);

    [OperationContract]
    [WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UpdateEmployee/{id}")]
    bool UpdateEmployee(Employee employee, string id);

    [OperationContract]
    [WebInvoke(Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Delete/{id}")]
    bool Delete(string id);
}    


Now we need a service class implementing interface methods.
Here we are using repository service to implement crud operations. Repository service will be created later in this post.
Rename Service1.cs file name with CrudService.cs. And write the below code in the file.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CrudService : ICrudService
{
    static IEmployeeRepository empRep = new EmpRepository();
    public List<Employee> GetAllEmployees()
    {
        try
        {
            return empRep.GetAllRepEmployees();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public Employee GetEmployee(string id)
    {
        try
        {
            return empRep.GetRepEmployee(id);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool AddEmployee(Employee employeeData)
    {
        try
        {
            empRep.AddRepEmployee(employeeData);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool UpdateEmployee(Employee employee, string id)
    {
        try
        {
            empRep.UpdateRepEmployee(employee, id);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool Delete(string id)
    {
        try
        {
            empRep.RemoveRepEmployee(id);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}


To Create Repository service we need to create an Interface having all the operation contract.
Add an Interface IEmployeeRepository.cs in the project. And write the below code in the file.

public interface IEmployeeRepository
{
    List<Employee> GetAllRepEmployees();
    Employee GetRepEmployee(string employeeID);
    void RemoveRepEmployee(string employeeID);
    void AddRepEmployee(Employee employee);
    void UpdateRepEmployee(Employee employee, string id);
}


To Implement repository operation contract we need a class. Create a class EmpRepository.cs implementing IEmployeeRepository interface.

public class EmpRepository : IEmployeeRepository
{
    private List<Employee> repEmp = new List<Employee>();
    public EmpRepository()
    {
        AddRepEmployee(new Employee { EmployeeID = "1", FirstName = "Hitesh", LastName = "Kumar", Address = "Gurgaon", DOB = "30/04/1990", Gender = "Male", Language = "Hindi", Nationality = "Indian" });
    }

    public void AddRepEmployee(Employee employee)
    {
        try
        {
            repEmp.Add(employee);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<Employee> GetAllRepEmployees()
    {
        try
        {
            return repEmp;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public Employee GetRepEmployee(string employeeID)
    {
        try
        {
            return repEmp.Where(e => e.EmployeeID == employeeID).First();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void RemoveRepEmployee(string employeeID)
    {
        try
        {
            repEmp.RemoveAll(e => e.EmployeeID == employeeID);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void UpdateRepEmployee(Employee employee, string id)
    {
        try
        {
            repEmp.RemoveAll(e => e.EmployeeID == id);
            repEmp.Add(employee);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}


To Access API we need to provide Authentication. So we need to add header to the request with the allowed origin. Here * is added to allow all the clients. Write the below code in the Global.asax file.

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (Context.Request.HttpMethod.Equals("OPTIONS"))
    {
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
        Context.ApplicationInstance.CompleteRequest();
    }
}


And in the last replace Web.config file with the below code.

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WCFCrudService.CrudService" behaviorConfiguration="Default">
        <endpoint name="webhttpBinding" address="" binding="webHttpBinding" contract="WCFCrudService.ICrudService" behaviorConfiguration="myServiceBehavior"></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="myServiceBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="Default">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>


And Finally WCF Rest API is ready. Build and Publish the API and host in your IIS Server and consume in your Application.