Creating WCF RESTful Service | WCF RESTful Guide | WCF Tutorial


A definition from Wikipedia, "Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web".

As we know that WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, Named Pipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just utilizing HTTP as a transport. But HTTP is much more than just a transport.

RESTful architecture use HTTP for all CRUD operations like (Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE).It’s simple as well as lightweight. For the sake of simplicity, I am going to implement only a GET request for which service will return certain types of data (i.e. Product data) in XML format.

1. Create a WCF Service Project
  •  Open Visual Studio.
  •  From File -> New Project.  Select WCF from left and create a new WCF Service Application.
2. Preparing the data to return
  • Now add a class to newly created project. Name it to Products.cs.
Now this Products.cs file will contain two things.First one is Data Contract
[DataContract]
public class Product
{
                 [DataMember]
                 public int ProductId { get; set; }
                 [DataMember]
                 public string Name { get; set; }
                 [DataMember]
                 public string CategoryName { get; set; }
                 [DataMember]
                 public int Price { get; set; }
}
Second one is a singleton implemented class that gets products data from a database and return list of products. In order to make it simple, we are preparing data inside this class instead of fetching from the database as follows:
public partial class Products
{
        private static readonly Products _instance = new Products();
        private Products() { } 
       public static Products Instance 
      { 
                get { return _instance; } 
       } 
        public List ProductList 
        { 
               get { return products; } 
         } 
          private List<Product> products = new List<Product>() 
         { 
                 new Product() { ProductId = 1, Name = “Product 1″, CategoryName = “Category 1″, Price=10}, 
                new Product() { ProductId = 1, Name = “Product 2″, CategoryName = “Category 2″, Price=5}, 
                new Product() { ProductId = 1, Name = “Product 3″, CategoryName = “Category 3″, Price=15}, 
                new Product() { ProductId = 1, Name = “Product 4″, CategoryName = “Category 1″, Price=9} 
         }; 
 }

3. Creating Service Contract
Now add a new WCF Service to this project as follows:

It will add contract as well as service file to project. Following is the code for service contract i.e. IProductRESTService.cs.
[ServiceContract]
public interface IProductRESTService
{
           [OperationContract]
           [WebInvoke(Method = "GET",
                                    ResponseFormat = WebMessageFormat.Xml,
                                   BodyStyle = WebMessageBodyStyle.Bare,
                                   UriTemplate = "GetProductList/")]
           List GetProductList();
}
IProductRESTService contains only one method i.e. GetProductList. Important points to understand about this method is WebInvoke attribute parameters.
  • Method = “GET”, represents an HTTP GET request.
  • ResponseFormat = WebMessageFormat.Xml, response format will be XML here but we can return JSON as well by changing its value to WebMessageFormat.json.
  • BodyStyle = WebMessageBodyStyle.Wrapped, indicates both the request and response are wrapped.
  • UriTemplate = “GetProductList/”, it has two parts, URL path and query.
Don’t forget to add using System.ServiceModel.Web at top.
4. Implementing RESTful Service
In this step we are going to implement the service. Only one method GetProductList is defined in the contract, so implementing service class will be as follows:
public class ProductRESTService : IProductRESTService
{
         public List GetProductList()
         {
                      return Products.Instance.ProductList;
          }
}

5. Configure Service and Behavior
The last step is to configure the service and its behaviors using the configuration file. Following is the complete ServiceModel configuration settings.
<system.serviceModel>
   <services>
        <service name=”MyRESTService.ProductRESTService” behaviorConfiguration=”serviceBehavior”>
                <endpoint address=””
                                       binding=”webHttpBinding”
                                       contract=”MyRESTService.IProductRESTService”
                                      behaviorConfiguration=”web”></endpoint>
          </service>
   </services>
   <behaviors>
          <serviceBehaviors>
              <behavior name=”serviceBehavior”>
                  <serviceMetadata httpGetEnabled=”true”/>
                       <serviceDebug includeExceptionDetailInFaults=”false”/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
              <behavior name=”web”>
                    <webHttp/>
               </behavior>
          </endpointBehaviors>
  </behaviors>
   <serviceHostingEnvironment multipleSiteBindingsEnabled=”true” />
</system.serviceModel>
 webHTTPBinding is the binding used for RESTful services.
Now, everything about creating RESTful service is done. Let us run and see it in action.
 
Right click ProductRESTService.svc file and click “View in Browser“. You will see the following screen, that means service is fine.
Just modify the URL in browser and add “GetProductList/” to it. So, this is the UriTemplete we defined as service contract method.