How to create WCF RESTful service.

This article describes step by step creation of WCF RESTful services and its HTTP methods like GET, PUT, DELETE, and POST. In this article, I am going to create a WCF REST service API that returns XML data as WCF attributes.

What is the RESTful WCF Service?

REST stands Representational state transfer works on HTTP protocols. Any clients like ASP.Net, C#, JAVA, jQuery who can communicate with HTTP protocols can consume the WCF REST services. REST is stateless, sessionless, and resource based architecture which helps you to easily access WCF service and reduce message size.

RESTful services use common HTTP verbs to perform operations.

  1. GET: Retrieves the resource.
  2. POST: Creates a new resource or submits data to be processed.
  3. PUT: Replace or update the entire content of resource.
  4. DELETE: Deletes the existing resource.

Benefits of using RESTful WCF Service.

  1. RESTful services provide several benefits over RPC style.
  2. Unlike SOAP it generates lightweight and much simpler human readable requests and responses resulting significant reduction in size.
  3. It has features like caching and interoperability as it uses HTTP protocols.
  4. It provides a uniform interface between client and service.
  5. RESTful services are best suited for internet facing applications where they can take benefits of HTTP features.

Follow the below steps to create your WCF RESTful service.

Create a new WCF Service Application

Open visual studio -> click on File -> New Project -> Create new WCF Service Application -> Name it as RESTFulWCFService.

WCF RESTful services

After creating an application from solution explorer. Remove default files IService.cs and Service.svc

Add WCF Restful ProductService

Right click on RESTFulWCFService application from solution explorer -> Select Add -> Select New Item -> Select WCF Service -> Name it as ProductService.

It will add two files ProductService.svc and IProductService.cs

WCF RESTful services

Products Service data store

Create a new XML file and name it as Products.xml and save it in C: drive. This XML file will be used as WCF service data base.

Add below XML data to the Products.xml

    
      <?xml version="1.0" standalone="yes" ?> 
      <DocumentElement>
          <Products>
              <productID>1</productID> 
              <productname>Chai</productname> 
              <categoryID>1</categoryID> 
              <UnitsInStock>39</UnitsInStock> 
              <CategoryName>Beverages</CategoryName> 
          </Products>
          <Products>
              <productID>2</productID> 
              <productname>Chang</productname> 
              <categoryID>1</categoryID> 
              <UnitsInStock>17</UnitsInStock> 
              <CategoryName>Beverages</CategoryName> 
          </Products>
          <Products>
              <productID>3</productID> 
              <productname>Aniseed Syrup</productname> 
              <categoryID>2</categoryID> 
              <UnitsInStock>13</UnitsInStock> 
              <CategoryName>Condiments</CategoryName> 
          </Products>        
      </DocumentElement> 
      

Create Operation Contracts

Add service operation contracts which can be accessed by clients. As we need to provide the RESTfulness we need to use WebGet or WebInvoke with these operations. As described in resources WebGet is used to retrieve the resources.

For this particular tutorial, all operations will be used to retrieve some data from Products.xml. So all operations will be used with WebGet.

Add below operation contracts to the IProductService.cs. Notice we have used WebGet and provided the UriTemplate. Any request with this particular Uri type will be served respective operation contracts.

    
using System.ServiceModel.Web;

namespace RESTFulWCFService
{   
    [ServiceContract]
    public interface IProductService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/ProductName/{productID}")]
        string GetProductName(string productID);

        [OperationContract]
        [WebGet(UriTemplate = "/ProductQty/{productID}")]
        string GetProductQty(string productID);

        [OperationContract]
        [WebGet(UriTemplate = "/ProductsCount")]
        string GetProductsCount();
    }
}
         

Implement IProductService

Open ProductService.svc and add code for retrieving data from Products.xml by implementing IProductService interface.

Add below code to ProductService.svc which adds implementation to each operation contract.

    
public class ProductService : IProductService
{
    public string GetProductName(string productID)
    {
        string productName = string.Empty;

        try
        {
            XDocument doc = XDocument.Load("C:\\products.xml");

            productName =
                (from result in doc.Descendants("DocumentElement")
                .Descendants("Products")
                    where result.Element("productID").Value 
                                == productID.ToString()
                    select result.Element("productname").Value)
                .FirstOrDefault<string>();
                
        }
        catch (Exception ex)
        {
            throw new FaultException<string>
                    (ex.Message);
        }
        return productName;
    }  
        
    public string GetProductQty(string productID)
    {
        string strProductQty = string.Empty; 

        try
        {
            XDocument doc = XDocument.Load("C:\\products.xml");
                 
            strProductQty =
                (from result in doc.Descendants("DocumentElement")
                .Descendants("Products")
                    where result.Element("productID").Value 
                            == productID.ToString()
                    select result.Element("UnitsInStock").Value)
                .FirstOrDefault<string>();
        }
        catch (Exception ex)
        {
            throw new FaultException<string>
                (ex.Message);
        }
        return strProductQty;
    }     

    public string GetProductsCount()
    {
        XDocument doc = XDocument.Load("C:\\products.xml");

        return doc.Descendants("Products").Count().ToString();
    }
}
        

Add service EndPoint

You need to use webHttpBinding for enabling service access through the browser or RESTfulness. Add below service endpoint to the web.config of Service Application.

Notice we have kept the address as empty and used binding as webHttpBinding. We can add endpointBehavior with <webHttp helpEnabled="true"/> to get help on errors. In the production environment you should disable it.

    
<system.serviceModel>
    <services>
        <service behaviorConfiguration="Default" 
                name="RESTFulWCFService.ProductService">
        <endpoint address="" behaviorConfiguration="webBehavior" 
                binding="webHttpBinding" 
                contract="RESTFulWCFService.IProductService" />
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" 
                    address="mex" />
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
        <behavior name="webBehavior">
            <webHttp helpEnabled="true"/>
        </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
        <behavior name="Default">
            <serviceMetadata httpGetEnabled="true"/>
        </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>
                    
         

Execute your WCF RESTful ProductService

From solution explorer right click on ProductService.svc file and select view in browser. It will show you the ProductService wsdl. Type the below URL in browser and see the result.

You will have to change the port number to port which you are using locally. While browsing the service do not forget to use UriTemplate exactly as you mentioned with OperationContract.

http://localhost:<Your port number>/ProductService.svc/ProductName/2

WCF RESTful Product Service result

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


  • geeksarray user
    12/30/2013 12:52 PM shashikant

    very nice article!

  • geeksarray user
    04/14/2015 05:01 AM vaneela

    WebClient proxy = new WebClient(); byte[] abc = proxy.DownloadData((new Uri("http://localhost:1248/service/Service.svc/Getcountry"))); Stream strm = new MemoryStream(abc); DataContractSerializer obj = new DataContractSerializer(typeof(DataTable)); string result = obj.ReadObject(strm).ToString(); DropDownList1.DataSource = result; DropDownList1.DataBind();

  • geeksarray user
    04/14/2015 05:01 AM vaneela

    WebClient proxy = new WebClient(); byte[] abc = proxy.DownloadData((new Uri("http://localhost:1248/service/Service.svc/Getcountry"))); Stream strm = new MemoryStream(abc); DataContractSerializer obj = new DataContractSerializer(typeof(DataTable)); string result = obj.ReadObject(strm).ToString(); DropDownList1.DataSource = result; DropDownList1.DataBind();