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 which returns XML data as WCF attributes.

What is 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 easy access to wcf service and reduce message size.


REST uses common http verbs to perform operations.

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

Benefits of using RESTful WCF Service.

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

Follow below steps to create your WCF RESTful service.


Create 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 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 data store

Create 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 this 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 IProductService.cs. Notice we have used WebGet and provided the UriTemplate. Any request with this particular Uri type will be served respective operation contract.

                
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 add 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 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 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

Download WCFRestFulService application with code

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by shashikant at 12/30/2013 12:52:00 PM
very nice article!
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by vaneela at 4/14/2015 5:01:00 AM
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();
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by vaneela at 4/14/2015 5:01:00 AM
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();
post comment on dotnetmentors.com