REST uses common http verbs to perform operations.
- GET: Retrieves the resource.
- POST: Creates new resource or submits data to be processed.
- PUT: Replace or update entire content of resource.
- DELETE: Deletes existing resource.
Benefits of using RESTful WCF Service.
- RESTful services provides several benefits over RPC style.
- Unlike SOAP it generates light weight and much simpler human readable request and
responses resulting significant reduction in size.
- It has features like caching and interoperability as it uses HTTP protocols.
- It provides uniform interface between client and service.
- 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.
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
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
Download WCFRestFulService application with code