joydip_kanjilal
Contributor

How to create a RESTful service in WCF

opinion
Apr 26, 20164 mins
Software Development

Take advantage of WCF to build light-weight RESTful services and keep the resource URIs clean and lean

WCF (Windows Communication Foundation) is a secure, reliable, and scalable messaging platform that can be used to build Web services in .Net. It provides a unified programming model for developing service oriented applications.

You can use WCF to build RESTful services in .NET. REST (Representational State Transfer) is an architecture paradigm that conforms to the REST architecture principles.The REST architecture is based on the concept of resources: It uses resources to represent the state and functionality of an application. These resources are in turn identified using URIs over the HTTP protocol.

Creating a WCF service

In this section we will explore how we can build a RESTful service in WCF. First off, let’s create a new WCF service in Visual Studio. To do this, follow the steps outlined below. Note that to build the application illustrated in this article I have used Visual Studio 2015 although you can use Visual Studio 2012 or 2013 as well.

  1. Open Visual Studio 2015
  2. In the File menu in the Visual Studio IDE, click on Start -> File -> New -> Project
  3. Next, select WCF from the list of the project templates displayed
  4. Select “WCF Service Application” on the right side pane
  5. Specify a name for your WCF service project and click OK to save it

This would create a new WCF Service Application project in the name you specified. The project would also contain a default service for illustration purposes only.

Implementing the RESTful WCF Service

When working with WCF, you first need to create a service contract and then define the service operations or operation contracts in it. Typically, a WCF service comprises of the following:

  1. Service class
  2. Service contract
  3. One or more operation contracts
  4. One or more endpoints
  5. Hosting environment

A ServiceContract is used to specify the operations that are available for the service client to consume.  The following code snippet shows how a service contract looks like — we will modify this later to make it RESTful.

 [ServiceContract]

    public interface ICustomerService

    {

        [OperationContract]

        List<Customer> GetCustomerList();

    }

A DataContract is used to describe the data that needs to be exchanged between the service provider and the service consumer. Consider the following DataContract called Customer.

[DataContract(Namespace = "")]

public class Customer

    {

        [DataMember]

        public Int32 CustomerID { get; set; }

        [DataMember]

        public string FirstName { get; set; }

        [DataMember]

        public string LastName { get; set; }

        [DataMember]

        public String Address { get; set; }

    }

An operation contract is used to expose a method as a service method and also transaction flow, direction of the service operation and also the fault contract(s) that may be associated. The following code snippet illustrates how you can declare a service operation using the OperationContract attribute and the use the WebInvoke attribute to specify the HTTP operation, Uri, Web message format, etc.

[OperationContract]

        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,

        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetCustomers")]

List<Customer> GetCustomerList();

The following code snippet illustrates how the customer service can be made RESTful by applying the WebInvoke attribute on its service method.

public interface ICustomerService

    {

        [OperationContract]

        [WebInvoke(Method = "GET",

            ResponseFormat = WebMessageFormat.Json,

            BodyStyle = WebMessageBodyStyle.Wrapped,

            UriTemplate = "GetCustomers")]

        List<Customer> GetCustomerList();

    }

The CustomerService class extends the ICustomerService service contract and provides the implementation of the service operation named GetCustomerList. Here’s how the CustomerService class would look like.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    public class CustomerService : ICustomerService

    {     

        public List<Customer> GetCustomerList()

        {

            return PopulateCustomerData();

        }

        private List<Customer> PopulateCustomerData()

        {

            List<Customer> lstCustomer = new List<Customer>();

            Customer customer1 = new Customer();

            customer1.CustomerID = 1;

            customer1.FirstName = "John";

            customer1.LastName = "Meaney";

            customer1.Address = "Chicago";

            lstCustomer.Add(customer1);

            Customer customer2 = new Customer();

            customer2.CustomerID = 1;

            customer2.FirstName = "Peter";

            customer2.LastName = "Shaw";

            customer2.Address = "New York";

            lstCustomer.Add(customer2);

            return lstCustomer;

        }

    }

Note that the PopulateCustomerData method is not a service method; it’s a private method that returns a list of customer records and is called from the GetCustomerList service method.

The next thing you should do is configure the WCF service. To do this, you would need to specify the binding and endpoint details and also the service behavior. The following code snippet shows how the service configuration should look like for this service.

<system.serviceModel>

    <services>

      <service name="IDGWCF.CustomerService" behaviorConfiguration="ServiceBehaviour">

        <endpoint address ="" binding="webHttpBinding" contract="IDGWCF.ICustomerService" behaviorConfiguration="web">

        </endpoint>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ServiceBehaviour">

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

  </system.serviceModel>

And that’s all you have to do. You can now open a Web browser and test your WCF RESTful service.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author