Channels ▼
RSS

.NET

Exposing RESTful Services Using WCF


Implementing the TestService WCF Service

More Insights

White Papers

More >>

Reports

More >>

Webcasts

More >>

The WCF Service class called TestService implements the WCF Service Contract implemented earlier -- it defines the two methods declared in the WCF Service Contract. Here's what the class looks like:


public class TestService : ITestService
    {
        public Employee GetEmployee(Int32 employeeID)
        {
            return new Employee { EmployeeID = employeeID, FirstName = "Joydip", LastName = "Kanjilal" };
        }
        public Employee PostEmployee(Int32 employeeID)
        {
            return new Employee { EmployeeID = employeeID, FirstName = "Joydip", LastName = "Kanjilal" };
        }
    }

Making TestService RESTful

To make your TestService RESTful you would need to specify the [WebGet] or the [WebInvoke] attributes in your Service Contract. While the former indicates that the WCF Service can respond to HTTP Get requests, the later is used to indicate that the WCF Service can respond to HTTP Post requests. Both of these belong to the System.ServiceModel.Web namespace and are actually part of the HTTP programming model for WCF.

The following code snippet illustrates how a typical [WebGet] attributeis defined:


[WebGet(UriTemplate = 
"/sales/getsales.xml",
  BodyStyle = WebMessageBodyStyle.Bare,
  RequestFormat = WebMessageFormat.Xml,
  ResponseFormat = WebMessageFormat.Xml)]

Similarly, here's how the [WebInvoke] attribute can be defined so that your WCF Service can respond to HTTP Post operations:


[GetOperationContract]
[WebInvoke(UriTemplate = 
"/sales/updatesales.xml?
productcode={code}",
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml)]

To make the service we created earlier in this article RESTful, just change the contract ITest and specify the WebGet attribute, as in the following code:


[ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebGet]
        Employee GetEmployee(Int32 employeeID);
        [WebInvoke]
        Employee PostEmployee(Int32 employeeID);
    }

Hosting the TestService

Once the service is built, you need to host it. To host a RESTful WCF Service you use the WebServiceHost factory, a class derived from the ServiceHost class. You should choose the WebServiceHostFactory if the service uses WebHttpBinding. If your service uses other types of binding, you can simply use the ServiceHostFactory to host the service.

To host TestService, create a Console application and add references to the following assemblies:

  • System.ServiceModel
  • System.ServiceModel.Description
  • System.ServiceModel.Web

Next, create an instance of the WebServiceHost factory class and pass the base address and the service type name as parameters:


Uri baseAddress = new Uri("http://localhost/RESTService");
WebServiceHost host = new WebServiceHost(typeof(TestService), baseAddress);

Now, specify the service endpoint and service debug behavior for your RESTful service. Here's the complete source code of the program that hosts the RESTful TestService:


using System;
using System.ServiceModel.Web;
using System.ServiceModel.Description;
using System.ServiceModel;
using RESTService;
namespace RESTServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost/RESTService");
            using (WebServiceHost host = new WebServiceHost(typeof(TestService), baseAddress))
            {
                ServiceEndpoint serviceEndpoint = host.AddServiceEndpoint(typeof(ITestService), new WebHttpBinding(), "http://localhost/RESTService/TestService.svc");
                ServiceDebugBehavior serviceDebugBehavior = host.Description.Behaviors.Find<ServiceDebugBehavior>();
                serviceDebugBehavior.HttpHelpPageEnabled = false;
                host.Open();
                Console.WriteLine("The TestService is up and running");
                Console.WriteLine("Press enter to terminate the TestService...");
                Console.ReadLine();
                host.Close();
            }
        }
    }
}

[Click image to view at full size]
Figure 2: The RESTful TestService is Started.

Consuming the TestService

Once your RESTful TestService is hosted, you can consume it from another application. To consume the RESTful WCF service we just created, you need to create an instance of the ChannelFactory class and pass the ServiceContract to it as the type. Next, you need to specify the type of binding to be used (WebHttpBinding in our example) and the address of the service. Once done, you can call the methods of the service on this channel. Here's the complete source code of the program that illustrates how you can consume the RESTful TestService:


using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using RESTService;
namespace RESTServiceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelFactory<ITestService> channelFactory = new ChannelFactory<ITestService>(new WebHttpBinding(), "http://localhost/RESTService");
            channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
            ITestService channel = channelFactory.CreateChannel();
            Console.WriteLine("Get Executed -  Name: " + channel.GetEmployee(1).FirstName + " " + channel.GetEmployee(1).LastName);
            Console.WriteLine("Post Executed -  Name: " + channel.PostEmployee(1).FirstName + " " + channel.GetEmployee(1).LastName);
            Console.Read();
        }
    }
}

When the client application is executed, here's what the output would look like:

[Click image to view at full size]
Figure 3: The Client for the RESTful TestService in Execution.


Related Reading






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video