Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#

A Beginner's Tutorial on Creating WCF REST Services

Rate me:
Please Sign up or sign in to vote.
4.82/5 (108 votes)
3 Apr 2013CPOL6 min read 619.5K   24.6K   163   65
In this article we will try to understand what are WCF REST services and how can we create one.

Introduction

In this article we will try to understand what are WCF REST services. We will see what is required from a service developers perspective to create a REST enabled WCF service. We see how we can use and consume restful WCF services.

Disclaimer: This is a rather old article(5 years almost). And I want to make a disclaimer here - This is not a REST service. This article talks about REST but ultimately end up creating the HTTP based service using WCF. This WCF service created is not following the REST architectural guidelines. Apologies for that(I guess we all get wiser with time). I will update the article but till then i feel like this disclaimer should be present. 

Background

Overview of REST

REST stands for Representational State Transfer. This is a protocol for exchanging data over a distributed environment. The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.

When we talk about the Database as a resource we usually talk in terms of CRUD operations. i.e. Create, Retrieve, Update and Delete. Now the philosophy of REST is that for a remote resource all these operations should be possible and they should be possible using simple HTTP protocols.

Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:

  • GET: This maps to the R(Retrieve) part of the CRUD operation. This will be used to retrieve the required data (representation of data) from the remote resource.
  • POST: This maps to the U(Update) part of the CRUD operation. This protocol will update the current representation of the data on the remote server.
  • PUT: This maps to the C(Create) part of the CRUD operation. This will create a new entry for the current data that is being sent to the server.
  • DELETE: This maps to the D(Delete) part of the CRUD operation. This will delete the specified data from the remote server.

so if we take an hypothetical example of a remote resource that contain a database of list of books. The list of books can be retrieved using a URL like:

www.testwebsite.com/books

To retrieve any specific book, lets say we have some ID that we can used to retrieve the book, the possible URL might look like:

www.testwebsite.com/books/1

Since these are GET requests, data can only be retrieved from the server. To perform other operations, if we use the similar URI structure with PUT, POST or DELETE operation, we should be able to create, update and delete the resource form the server. We will see how this can be done in implementation part.

Note: A lot more complicated queries can be performed using these URL structures. we will not be discussing the complete set of query operations that can be performed using various URL patterns.

Using the code

Now we can create a simple WCF service that will implement all the basic CRUD operations on some database. But to make this WCF service REST compatible we need to make some changes in the configuration, service behaviors and contracts. Let us see what WCF service we will be creating and then we will see how we can make useful over the REST protocol.

creating REST enabled ServiceContract

We will create Books table and will try to perform CRUD operations on this table. 

Image 1

 

To perform the Database operations within the service lets use Entity framework. This can very well be done by using ADO.NET calls or some other ORM but I chose entity framework. (please refer this to know about entity framework:  An Introduction to Entity Framework for Absolute Beginners[^]). The generated Entity will look like following. 

 

Image 2

Now the service contract will contain functions for CRUD operations. Let us create the ServiceContract for this service:

C#
[ServiceContract]
public interface IBookService
{
    [OperationContract]
    List<Book> GetBooksList();

    [OperationContract]
    Book GetBookById(string id);

    [OperationContract]
    void AddBook(string name);

    [OperationContract]
    void UpdateBook(string id, string name);

    [OperationContract]
    void DeleteBook(string id);
}

Right now this is a very simple service contract, to indicate that individual operations can be called using REST protocol, we need to decorate the operations with additional attributes. The operations that are to be called on HTTP GET protocol, we need to decorate them with the WebGet attribute. The operations that will be called by protocols, like POST, PUT, DELETE will be decorated with WebInvoke attribute.

Understanding UriTemplate

Now before adding these attributes to these operations let us first understand the concept of UriTemplate. UriTemplate is a property of WebGet and WebInvoke attribute which will help us to map the parameter names coming from the HTTP protocol with the parameter names of ServiceContract. For example, if someone uses the following URI:

localhost/testservice/GetBookById/2

We need to map this first parameter with the id variable of the function. this can be done using the UriTemplate. Also, we can change the function name specifically for the URI and the name of URI function name will be mapped to the actual function name i.e. if we need to call the same URL as:

localhost/testservice/Book/2

then we can do that by specifying the UriTemplate for the operation as:

C#
[OperationContract]
[WebGet(UriTemplate  = "Book/{id}")]
Book GetBookById(string id);

Following the same lines, let us define the UriTemplate for other methods too.

C#
[ServiceContract]
public interface IBookService
{
    [OperationContract]
    [WebGet]
    List<Book> GetBooksList();

    [OperationContract]
    [WebGet(UriTemplate  = "Book/{id}")]
    Book GetBookById(string id);

    [OperationContract]
    [WebInvoke(UriTemplate = "AddBook/{name}")]
    void AddBook(string name);

    [OperationContract]
    [WebInvoke(UriTemplate = "UpdateBook/{id}/{name}")]
    void UpdateBook(string id, string name);

    [OperationContract]
    [WebInvoke(UriTemplate = "DeleteBook/{id}")]
    void DeleteBook(string id);
}

Implementing the Service  

Now the service implementation part will use the entity framework generated context and entities to perform all the respective operations.

C#
public class BookService : IBookService
{
    public List<Book> GetBooksList()
    {
        using (SampleDbEntities entities = new SampleDbEntities())
        {
            return entities.Books.ToList();
        }
    }

    public Book GetBookById(string id)
    {
        try
        {
            int bookId = Convert.ToInt32(id);

            using (SampleDbEntities entities = new SampleDbEntities())
            {
                return entities.Books.SingleOrDefault(book => book.ID == bookId);
            }
        }
        catch
        {
            throw new FaultException("Something went wrong");
        }
    }

    public void AddBook(string name)
    {
        using (SampleDbEntities entities = new SampleDbEntities())
        {
            Book book = new Book { BookName = name };
            entities.Books.AddObject(book);
            entities.SaveChanges();
        }
    }

    public void UpdateBook(string id, string name)
    {
        try
        {
            int bookId = Convert.ToInt32(id);

            using (SampleDbEntities entities = new SampleDbEntities())
            {
                Book book = entities.Books.SingleOrDefault(b => b.ID == bookId);
                book.BookName = name;
                entities.SaveChanges();
            }
        }
        catch
        {
            throw new FaultException("Something went wrong");
        }
    }

    public void DeleteBook(string id)
    {
        try
        {
            int bookId = Convert.ToInt32(id);

            using (SampleDbEntities entities = new SampleDbEntities())
            {
                Book book = entities.Books.SingleOrDefault(b => b.ID == bookId);
                entities.Books.DeleteObject(book);
                entities.SaveChanges();
            }
        }
        catch
        {
            throw new FaultException("Something went wrong");
        }
    }
}

Restful WCF service Configuration

Now from the ServiceContract perspective the service is ready to serve the REST request but to access this service over rest we need to do some changes in the service behavior and binding too.

To make the service available over REST protocol the binding that needs to be used is the webHttpBinding. Also, we need to set the endpoint's behavior configuration and define the webHttp parameter in the endpointBehavior. So our resulting configuration will look something like:

Image 3

 

Test the service

 

Now to test the service we will simply run the service and use the URLs to retrieve the data. let see this for our GET operations in action.

Image 4 

And now testing the query to get a single record

Image 5 

And so we have seen that we received the response in the browser itself in form of XML. We can use this service without even consuming it by adding a service reference by using the URLs and HTTP protocols.

Note: Here I am not demonstrating the other operations for POST, PUT and DELETE but they are fairly straight forwards and a simple HTML page sending the data using the required protocol with the specified parameter names will perform the operation.

Using JSON

We can also change the Response and Request format to use JSON instead of XML. To do this we need to specify properties of the WebInvoke attribute.

  • RequestFormat: By default its value is WebMessageFormat.XML. to change it to JSON format, it needs to be set to WebMessageFormat.Json.
  • ResponseFormat: By default its value is WebMessageFormat.XML. to change it to JSON format, it needs to be set to WebMessageFormat.Json.

Let us create one more operation in our service contract called as GetBooksNames and will apply the ResponseFormat as Json for this method.

C#
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json]
List<string> GetBooksNames();

The response will now appear in the JSON format. 

Image 6

 

And now we have a WCF REST service ready with us.

 

Note: We also have a ready made template in Visual studio to create WCF data services that provides us with easy way to create REST enabled ODATA services. We will perhaps talk about them separately.

Point of interest

In this article we have seen how we can create REST enabled WCF services. We have also looked at a sample application for implementing the same. A lot has been left for the reader as an exercise(like operations using POST, PUT and DELETE) but still I hope this has been somewhat informative.

History

  • 03 April 2013: First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralAddition to POI Pin
Daniel Kienböck26-Jun-16 10:26
Daniel Kienböck26-Jun-16 10:26 
GeneralGood article but having trouble hosting Pin
csugden14-Apr-16 7:51
professionalcsugden14-Apr-16 7:51 
QuestionShort and clear Pin
Member 76768487-Nov-15 4:52
Member 76768487-Nov-15 4:52 
GeneralMy vote of 3 Pin
Stoykovnet8-Oct-15 1:22
Stoykovnet8-Oct-15 1:22 
GeneralRe: My vote of 3 Pin
BerndVP28-Jan-16 21:12
BerndVP28-Jan-16 21:12 
QuestionEndPoint is not visible at client program.. Pin
vvlktvsv10-Jun-15 9:14
vvlktvsv10-Jun-15 9:14 
AnswerRe: EndPoint is not visible at client program.. Pin
Rahul Rajat Singh10-Jun-15 18:21
professionalRahul Rajat Singh10-Jun-15 18:21 
GeneralRe: EndPoint is not visible at client program.. Pin
vvlktvsv17-Jun-15 8:11
vvlktvsv17-Jun-15 8:11 
QuestionEndpoint not found Pin
Zek Patafta2-Mar-15 23:24
Zek Patafta2-Mar-15 23:24 
GeneralThis article is good one Pin
Member 1095577315-Jan-15 21:23
Member 1095577315-Jan-15 21:23 
GeneralMy vote of 1 Pin
BrianLeBlanc5-Jan-15 2:40
BrianLeBlanc5-Jan-15 2:40 
QuestionBook object Pin
codemasterin19-Dec-14 10:19
codemasterin19-Dec-14 10:19 
GeneralMy vote of 1 Pin
BrianLeBlanc18-Dec-14 4:45
BrianLeBlanc18-Dec-14 4:45 
QuestionHow to Use This WCF Rest Api in to MVC Application Pin
Satish “శ్రీ” sri16-Oct-14 2:34
Satish “శ్రీ” sri16-Oct-14 2:34 
SuggestionOverview of REST Correction Pin
cpg_md@yahoo.com14-Oct-14 4:45
cpg_md@yahoo.com14-Oct-14 4:45 
GeneralThanks! Pin
ivike3-Oct-14 4:20
ivike3-Oct-14 4:20 
GeneralMy vote of 5 Pin
Yamin Khakhu12-Sep-14 17:12
professionalYamin Khakhu12-Sep-14 17:12 
QuestionThank you Pin
Member 1102636525-Aug-14 4:08
Member 1102636525-Aug-14 4:08 
QuestionREST is Simple Pin
j_hawthor22-Aug-14 1:07
j_hawthor22-Aug-14 1:07 
QuestionUnable to pull the service Pin
Member 1093763021-Aug-14 3:25
Member 1093763021-Aug-14 3:25 
GeneralMy vote of 5 Pin
Member 1026445924-Jul-14 5:04
Member 1026445924-Jul-14 5:04 
This is very useful for me as i am not aware of REST
GeneralBeware of ServiceHost while hosting a WCF restful service Pin
Rasik Bihari Tiwari14-Jul-14 22:51
professionalRasik Bihari Tiwari14-Jul-14 22:51 
GeneralRe: Beware of ServiceHost while hosting a WCF restful service Pin
tomparkinson16-Sep-14 5:53
tomparkinson16-Sep-14 5:53 
QuestionPlz Solve this question as soon as possible Pin
Member 109336008-Jul-14 15:57
Member 109336008-Jul-14 15:57 
AnswerRe: Plz Solve this question as soon as possible Pin
PIEBALDconsult8-Jul-14 16:10
mvePIEBALDconsult8-Jul-14 16:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.