Create a WCF RESTful Service

Overview

WCF

Windows Communication Foundation (WCF) is a distributed technology that provides a single, integrated platform or mode called the service mode to develop distributed applications for Windows. With WCF, powerful and interoperable service-oriented applications can be developed. It is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication and also uses Simple Object Access Protocol (SOAP) messages to exchange information between a service and client.

  • Service Contract

    Service contract is an attribute applied to an interface such as IService1. It describes which operations the client can perform on the services.

  • Operation Contract

    Operation Contract is an attribute applied to methods in interfaces such as IService1. It defines a method in an interface. It defines the input parameters and the return type of a specific Operation in the service.

  • Data Contract

    The DataContract defines which data types are passed to and from the service. It defines a class and the DataMember attribute defines the properties.

REST

Representational State Transfer (REST) is a protocol for exchanging data over a distributed environment. The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.

JSON

The JavaScript Object Notation (JSON) data format, or JSON for short, is derived from the literals of the JavaScript programming language. JSON helps us to present and exchange data in a self-descriptive, independent and light way. This data can then be easily consumed and transformed into JavaScript objects.

In most browser-based applications, WCF can be consumed using JavaScript, jQuery, AngularJs and so on. When a client makes a call to WCF, JSON or XML is used as the format of the communication. WCF has the option to send the response in JSON object. This can be configured with the WebGet or WebInvoke attribute and the WebHttpBinding. This allows you to expose a ServiceContract as a REST service that can be invoked using either JSON or plain XML.

  • GET: Retrieves the information.
  • PUT: Replaces the entire collection with another collection.
  • POST: Creates a new entry in the collection.
  • DELETE: Deletes the entire collection.

First we need to create the WCF REST Service. So use the following procedure.

Open Visual Studio and select "File", then "New" and "Project...". Then select WCF in the left side, click WCF Service Application. Click OK.

IService

Now delete the IService.cs and Service.cs files.

Customer Service

Now right-click on the project in the Solution Explorer and select Add New Item, then select WCF Service and name it Customer Service.

WCF SErvice

Now I will create a Data Contract CustomerDataContract.

Right-click on the project in the Solution Explorer and select Add New Item. Then add a .cs file and use the following code:

class

CustomerDataContract.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.Web;  
  6.   
  7. namespace WCFRESTfulService  
  8. {  
  9.     [DataContract]  
  10.     public class CustomerDataContract  
  11.     {  
  12.         [DataMember]  
  13.         public string CustomerID { getset; }  
  14.         [DataMember]  
  15.         public string CompanyName { getset; }  
  16.         [DataMember]  
  17.         public string ContactName { getset; }  
  18.         [DataMember]  
  19.         public string ContactTitle { getset; }  
  20.         [DataMember]  
  21.         public string Address { getset; }  
  22.         [DataMember]  
  23.         public string City { getset; }  
  24.         [DataMember]  
  25.         public string Region { getset; }  
  26.         [DataMember]  
  27.         public string PostalCode { getset; }  
  28.         [DataMember]  
  29.         public string Country { getset; }  
  30.         [DataMember]  
  31.         public string Phone { getset; }  
  32.         [DataMember]  
  33.         public string Fax { getset; }  
  34.     }  
  35. }  
Now it is time to add your database to the application. So create a new folder named Model in your project.

create a new folder

Now right-click on the Model folder and select Add, then click New Item.

Add new item

Select the ADO.NET Entity Data Model.

ADO DOT NET

Right-click the Customer entity and choose Generate Database from Model on the context menu. You'll see the Generate Database Wizard dialog box, as shown here:

crate connection

Here click on New Connection then enter your SQL Server Details and then select your database.

Select database

data connection

click finish

model

Now open the ICustomerService.cs file to define an interface as in the following:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8.   
  9. namespace WCFRESTfulService  
  10. {  
  11.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICustomerService" in both code and config file together.  
  12.     [ServiceContract]  
  13.     public interface ICustomerService  
  14.     {  
  15.         [OperationContract]  
  16.         [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,  
  17.             ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAllCustomer/")]  
  18.         List<CustomerDataContract> GetAllCustomer();  
  19.   
  20.         [OperationContract]  
  21.         [WebGet( RequestFormat = WebMessageFormat.Json,  
  22.            ResponseFormat = WebMessageFormat.Json,  
  23.            UriTemplate = "/CustomerDetails/{CustomerID}")]  
  24.         CustomerDataContract CustomerDetails(string customerID);  
  25.     }  
  26. }  
CustomerService.svc

Code

CustomerService
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7.   
  8. //  
  9. using WCFRESTfulService.Model;  
  10.   
  11. namespace WCFRESTfulService  
  12. {  
  13.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CustomerService" in code, svc and config file together.  
  14.     // NOTE: In order to launch WCF Test Client for testing this service, please select CustomerService.svc or CustomerService.svc.cs at the Solution Explorer and start debugging.  
  15.     public class CustomerService : ICustomerService  
  16.     {  
  17.         NorthwindEntities dc;   
  18.         public CustomerService()  
  19.         {  
  20.             dc = new NorthwindEntities();  
  21.         }  
  22.         public List<CustomerDataContract> GetAllCustomer()  
  23.         {  
  24.             var query = (from a in dc.Customers  
  25.                          select a).Distinct();  
  26.   
  27.             List<CustomerDataContract> CustomersList = new List<CustomerDataContract>();  
  28.   
  29.             query.ToList().ForEach(x =>  
  30.             {  
  31.                 CustomersList.Add(new CustomerDataContract  
  32.                 {  
  33.                     CustomerID = Convert.ToString(x.CustomerID),  
  34.                     CompanyName = x.CompanyName,  
  35.                     ContactName = x.ContactName,  
  36.                     ContactTitle = x.ContactTitle,  
  37.                     Address = x.Address,  
  38.                     City = x.City,  
  39.                     Region = x.Region,  
  40.                     PostalCode = x.PostalCode,  
  41.                     Country = x.Country,  
  42.                     Phone = x.Phone,  
  43.                     Fax = x.Fax,                     
  44.                 });  
  45.             });  
  46.             return CustomersList;  
  47.         }  
  48.   
  49.         public CustomerDataContract CustomerDetails(string customerID)  
  50.         {  
  51.             CustomerDataContract Cust = new CustomerDataContract();             
  52.             try  
  53.             {                  
  54.                 var query = (from a in dc.Customers  
  55.                              where a.CustomerID.Equals(customerID)  
  56.                              select a).Distinct().FirstOrDefault();  
  57.                 Cust.CustomerID = query.CustomerID;  
  58.                 Cust.CompanyName = query.CompanyName;  
  59.                 Cust.ContactName = query.ContactName;  
  60.                 Cust.ContactTitle = query.ContactTitle;  
  61.                 Cust.Address = query.Address;  
  62.                 Cust.City = query.City;  
  63.                 Cust.Region = query.Region;  
  64.                 Cust.PostalCode = query.PostalCode;  
  65.                 Cust.Country = query.Country;  
  66.                 Cust.Phone = query.Phone;  
  67.                 Cust.Fax = query.Fax;   
  68.             }  
  69.             catch (Exception ex)  
  70.             {  
  71.                 throw new FaultException<string> (ex.Message);  
  72.             }  
  73.             return Cust;  
  74.         }  
  75.     }  
  76. }  
Now make the following changes in your WCF application web.config file:

web config file

Now our WCF REST Service is ready. Run the WCF REST service.

http://localhost:1040/CustomerService.svc/GetAllCustomer/

WCF REST service

You will see the following output http://localhost:1040/CustomerService.svc/GetAllCustomer/

You will see below output

You will see the following output http://localhost:1040/CustomerService.svc/CustomerDetails/ALFKI

output

I hope this article is useful. If you have any other questions then please mention it in the comments section.

 

Up Next
    Ebook Download
    View all
    Learn
    View all