REST (Representational State Transfer) is basically an architectural style that is based on the same principles as that of “Web”. In this WCF Service tutorial we are going to see these web principles in action. We will be using standard HTTP verbs for CRUD (Create, Retrieve, Update, Delete) operations, HTTP Content-Types etc.In one of my previous articles, I explained 5 simple steps to create your first RESTful web service. In part-1 of this article, we will build a RESTful web serviceusingWCF while in second part, we will be consuming the web service using jQuery.

Download the Complete Source Code for this WCF Tutorial

Let’s start by creating a WCF Service Application Project using Visual Studio. For the purpose of this implementation, I am using Visual Studio 2013.

Open Visual Studio 2013, From File -> New Project -> WCF Service Application.

Before creating WCF REST Service, let’s prepare object that represents data in our application i.e. DataContract class. Right click on newly created project in Visual Studio 2013 and go to Add -> Class and name it as “Books.cs”.

Following is the code for our DataContract class i.e. “Book”.

Don’t forget to add System.ServiceModel and System.Runtime.Serialization as mentioned above.

and as mentioned above. Also note that we have created WCF DataContract class “Book” but the file name is “Books.cs”. Although it doesn’t make any difference but just clarifying as we will be adding below BookRepository to same physical file (Books.cs).

For the purpose of simplicity, we are not going to write code for interacting with database. Instead we will separate code for actual CRUD operations using repository design pattern. Benefit of using repository pattern approach is that we can easily replace the implementation with actual database interaction code according to our own need.

We will create an interface “IBookRepository” as follows:

and implementing class “BookRepository” for our above interface is as follows:

public class BookRepository : IBookRepository

{

private List<Book> books = new List<Book>();

private int counter = 1;



public BookRepository()

{

AddNewBook(new Book { Title = “Thinking in C#”, ISBN = “65674523432423” });

AddNewBook(new Book { Title = “Thinking in Java”, ISBN = “34223434543423” });

AddNewBook(new Book { Title = “Beginning WCF”, ISBN = “35343532423” });

}

//CRUD Operations

//1. CREAT

public Book AddNewBook(Book newBook)

{

if (newBook == null)

throw new ArgumentNullException(“newBook”); newBook.BookId = counter++;

books.Add(newBook);

return newBook;

}

//2. RETRIEVE /ALL

public List GetAllBooks()

{

return books;

}

//2. RETRIEVE /By BookId

public Book GetBookById(int bookId)

{

return books.Find(b => b.BookId == bookId);

}

//3. UPDATE

public bool UpdateABook(Book updatedBook)

{

if (updatedBook == null)

throw new ArgumentNullException(“updatedBook”);

int idx = books.FindIndex(b => b.BookId == updatedBook.BookId);

if (idx == -1)

return false; books.RemoveAt(idx);

books.Add(updatedBook);

return true;

}

//4. DELETE

public bool DeleteABook(int bookId)

{

int idx = books.FindIndex(b => b.BookId == bookId);

if (idx == -1)

return false; books.RemoveAll(b => b.BookId == bookId);

return true;

}

}

As we are going to perform CRUD operations using RESTful service, we must know that how these actions map to standard HTTP verbs.

Method Action GET Getting a specific representation of a resource. In our case, get all books or get a book by a specific ID are relevant actions. PUT Create/Update a resource. Add a new book or update an existing book. DELETE Delete a resource. Delete an existing book. POST Submit data to a resource.

Now, it’s time to add WCF Service to our project. Simply right click on project in Visual Studio 2013 and go to Add -> WCF Service as shown in below screenshot and name our service as “BookService“.

It will add two new files to project:

IBookService.cs BookService.svc

Following is the code for WCF Service Contract i.e. IBookService:

Service exposes methods for all CRUD operations. Major things to understand about above code are:

WebInvoke attribute is used to expose services using HTTP verbs like GET, POST, PUT, DELETE etc.

Method is the HTTP verb used for a specific action already explained above.

is the HTTP verb used for a specific action already explained above. RequestFormat is the request message format e.g. JSON, XML etc.

is the request message format e.g. JSON, XML etc. ResponseFormat is the response message format e.g. JSON, XML etc.

is the response message format e.g. JSON, XML etc. UriTemplate is the unique URI for each specific service operations. Service consumer only knows about unique URI defined in UriTemplate.

Implementation code of BookService for all operations is as follows:

Above screenshot clearly show the BookService.svc implementing IBookService interface with GET methods implementation using our repository created earlier.

GetBookList() returns list of books, while

returns list of books, while GetBookById() returns a single Book by given id.

Code for GET methods is self-explainatory.

Now, In order to Add a new Book or update an existing Book record, we will implement AddBook & UpdateBook WCF REST Service methods as follows:

And finally the Delete REST method for deleting an existing Book record from our repository:

So the implementation for all CRUD (Create, Retrieve, Update, Delete) operations of our WCF RESTful Service is complete now. We will do the required configuration settings for our REST based Service.

Configuration settings for the service given below. I have placed the complete configuration for <system.serviceModel>.

<system.serviceModel>

<services>

<service name=”RESTServiceCRUD.BookService”

behaviorConfiguration=”serviceBehavior”>

<endpoint address=””

binding=”webHttpBinding”

contract=”RESTServiceCRUD.IBookService”

behaviorConfiguration=”RESTEndpointBehavior”></endpoint>

</service>

</services>

<behaviors>

<endpointBehaviors>

<behavior name=”RESTEndpointBehavior”>

<webHttp />

</behavior>

</endpointBehaviors>

<serviceBehaviors>

<behavior name=”serviceBehavior”>

<serviceMetadata httpGetEnabled=”false” />

<serviceDebug includeExceptionDetailInFaults=”false” />

</serviceBehaviors>

</behaviors>

</system.serviceModel>

Above configuration is pretty similar like normal WCF service except the following.

webHttpBinding is the binding specifically introduced for RESTful services in Windows Communication Foundation version 3.5.

is the binding specifically introduced for RESTful services in Windows Communication Foundation version 3.5. endpointBehavior is “webHttp” for RESTful service.

We are done with implementation of all CRUD(Create, Retrieve, Update, Delete) operations for a WCF RESTful service. Let’s just verify by right clicking on BookService.svc and press “View in Browser“, we will get the following browser window.

We will consume this service by calling all service methods through jQuery code in Part-2 of this WCF REST Tutorial but lets see the results for few calls here to understand the configuration settings and other related concepts.

For example, In order to get all book records, we will modify the URL in browser window as follows:

http://localhost:XXX/BookService.svc/Books” and it displays for download of Books.json at the bottom of the browser window. If we press the Open button to see the contents of Books.json, it will be something as below: As you can see that we modify the browser URL with “” and it displays for download ofat the bottom of the browser window. If we press the Open button to see the contents of Books.json, it will be something as below:

You can see the results from WCF RESTful Service in JSON format of the data we put in our repository class.

As we discussed earlier about WebInvoke attributes of IBookService interface, we can conclude few points here as:

Name of our GET method was GetBooksList() but in WebInvoke attribute UriTemplate, we provided the URI as “Books/” means we will access the RESTful service as:

http://localhost:xxxx/BookService.svc/Books/

but in WebInvoke attribute UriTemplate, we provided the URI as “Books/” means we will access the RESTful service as: http://localhost:xxxx/BookService.svc/Books/ ResponseFormat = WebMessageFormat.Json, so output is JSON format. If we modify and change it to WebMessageFormat.Xml, the same method call will output in XML format as follows:

Now, lets move to Part-2 of this WCF tutorial series, we will consume all these operations.