How to create WCF Restful Services

Rama Sagar
Posted by in WCF category on for Beginner level | Points: 250 | Views : 6976 red flag
Rating: 4 out of 5  
 1 vote(s)

REST stands for Representational state transfer which works on HTTP protocols. ASP.net,JAVA,j Query who can communicate with HTTP protocols can consume with WCF REST services. REST is stateless, session-less and resource based architecture which gives easy access to wcf service and reduce message size.

Introduction


This article gives a walk through of creating  WCF Restful services and its HTTP methods like GET, PUT, DELETE and POST.Here I am going to create a WCF rest service API which returns XML data as WCF attribute.


 REST uses the following common HTTP verbs

  • 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.

Lets Implement the Service

    •   Step 1   Create a New WCF service Application  Open visual studio -> click on File -> New Project -> Create new WCF Service Application -> Name it as SampleRESTFulWCFService.
 After the application creation Remove the default files IService.cs and Service.svc from solution explorer
    • Step 2  Now add WCF Service 
               Right click on SampleRESTFulWCFService application from solution explorer -> Select Add -> Select New          Item -> Select WCF Service -> Name it as BooksService as shown below

          It will add two files BooksService.svc and IBooksService.cs 

                   





Step 3 Now Lets Create a Xml File named Books.Xml add the data below and save it..we will use this as a database..

<?xml version="1.0" standalone="yes" ?> 
      <DocumentElement>
          <Books>
              <BookID>1</BookID> 
              <Booksname>Compilers</Booksname> 
              <categoryID>1</categoryID> 
              <UnitsInStock>39</UnitsInStock> 
              <CategoryName>AcademicBooks</CategoryName> 
          </Books>
          <Books>
              <BookID>2</BookID> 
              <Booksname>SCJP</Booksname> 
              <categoryID>1</categoryID> 
              <UnitsInStock>17</UnitsInStock> 
              <CategoryName>AcademicBooks</CategoryName> 
          </Books>
          <Books>
              <BookID>3</BookID> 
              <Booksname>SAP</Booksname> 
              <categoryID>2</categoryID> 
              <UnitsInStock>13</UnitsInStock> 
              <CategoryName>AcademicBooks</CategoryName> 
          </Books>        
      </DocumentElement>


 
  Step 4   Now Lets Create Operation Contracts
 
  We have to use Webget or WebInvoke with this operations inorder to provide Restfullness Webget is used to    retrieve the resources.As we need to retreive data from Books.Xml file we have used Webget and provided    the UriTemplate for all operations.Inorder to use Webget we have to add using System.ServiceModel.Web Namespace..

Now Add the below operation contracts to IBooksService.cs file


using System.ServiceModel;
using System.ServiceModel.Web;

namespace SampleRESTFulWCFService

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IBooksService" in both code and config file together.
{
    [ServiceContract]
    public interface IBooksService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/Booksname/{BookID}")]
        string GetBooksName(string BookID);

        [OperationContract]
        [WebGet(UriTemplate = "/BooksQty/{BookID}")]
        string GetBooksQty(string BookID);

        [OperationContract]
        [WebGet(UriTemplate = "/BooksCount")]
        string GetBooksCount();
    }
}

     
   


Step 5 Now Lets Implement the IBooksService

Add below code to retrieve data from XML file
 
using System;
using System.Linq;
using System.ServiceModel;
using System.Xml.Linq;

namespace SampleRESTFulWCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BooksService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select BooksService.svc or BooksService.svc.cs at the Solution Explorer and start debugging.
    public class BooksService : IBooksService
    {
        public string GetBooksName(string BookID)
        {
            string Booksname = string.Empty;

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

                Booksname =
                    (from result in doc.Descendants("DocumentElement")
                    .Descendants("Books")
                     where result.Element("BookID").Value == BookID.ToString()
                     select result.Element("Booksname").Value)
                    .FirstOrDefault<string>();

            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                     (ex.Message);
            }
            return Booksname;
        }

        public string GetBooksQty(string BookID)
        {
            string strBooksQty = string.Empty;

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

                strBooksQty =
                    (from result in doc.Descendants("DocumentElement")
                    .Descendants("Books")
                     where result.Element("BookID").Value == BookID.ToString()
                     select result.Element("UnitsInStock").Value)
                    .FirstOrDefault<string>();
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                   (ex.Message);
            }
            return strBooksQty;
        }

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

            return doc.Descendants("Books").Count().ToString();
        }
    }
}
   
                  Step 6  Add Service EndPoint

     
we need to use webHttpBinding  inorder to access service through browser.Add the below service endpoint to the web.config file.

 Note: Here we kept the address as empty and we used webHttpBinding inorder to get assistance on errors.

<system.serviceModel>
    <services>
      <service behaviorConfiguration="Default"
                name="SampleRESTFulWCFService.BooksService">
        <endpoint address="" behaviorConfiguration="webBehavior"
                binding="webHttpBinding" contract="SampleRESTFulWCFService.IBooksService" />
        <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>

Now Lets Browse the Service 




 

Conclusion


In this article we have implemented Restful Service.Please let me any issues through your comments.Thanks For reading my article.

Reference

http://msdn.microsoft.com/en-us/magazine/dd315413.aspx

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Posted by: Gundamadhu on: 10/10/2013 | Points: 25
I am not able to invoke the service through browser with above configuration changes. I don't see the option in the browser with the url to invoke. I am pasting the web.config file code here to analyze the issue.
<?xml version="1.0"?>

<configuration>

<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="Default" name="SampleRESTFulWCFService.BooksService">
<endpoint address="" binding="wsHttpBinding" contract="SampleRESTFulWCFService.IBooksService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Default">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->
</system.serviceModel>
</configuration>

Posted by: Rama Sagar on: 10/8/2013 | Points: 25
Hi GundaMadhu I cant able to see your config file..Please copy it in notepad and then copy paste here.or use a code block

Login to post response

Comment using Facebook(Author doesn't get notification)