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.
- 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:
{
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” });
}
//1. CREAT
public Book AddNewBook(Book newBook)
{
if (newBook == null)
throw new ArgumentNullException(“newBook”); newBook.BookId = counter++;
books.Add(newBook);
return newBook;
}
public List GetAllBooks()
{
return books;
}
public Book GetBookById(int bookId)
{
return books.Find(b => b.BookId == bookId);
}
public bool UpdateABook(Book updatedBook)
{
if (updatedBook == null)
throw new ArgumentNullException(“updatedBook”);
if (idx == -1)
return false; books.RemoveAt(idx);
books.Add(updatedBook);
return true;
}
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.
[su_table]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.
- RequestFormat is the request message format e.g. JSON, XML etc.
- ResponseFormat 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.
- GetBookList() 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>.
<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.
- endpointBehavior is “webHttp” for RESTful service.
- 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/ - 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:
- Top 10 WCF Interview Questions
- WCF Interview Questions – Comprehensive Parts Series
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET AJAX Interview Questions
did you try the PUT and POST method? it didn’t work.. can you tell us to make it right? thanks
HI,
whenver i change PUT to POST..it doesnt work…Please suggest.
Thanks.
Hi,
How can I add authentication(ie, username and password) into the project?
Thanks.
Hi Frankie,
Soon, I’ll provide code for authentication.
Just keep in touch.
Regards,
Imran
There is the service definitions. But when I click to http://localhost:56601/BookService.svc/GetBookList, it return Endpoint not found.
What is the reason?
Hi,
I have updated this WCF RESTful Service Tutorial to clarify the things you mentioned above. Also, I have provided the complete source code for download. You can download and check again. If the problem persist, please let me know.
Thanks,
Imran
Hi,
I have created the service by following the above steps. Can i test this bookservice by using wcf test client ?
I tried using testclient to test the service but none of the service methods are being exposed.
Will be very much thankfull for your help.
Thanks
Ayaz
Hi Ayaz,
I have provided Part-2 for consuming the service that you can use to test.
As far as WCF Test client is concerned, it’s REST based Service, web endpoints do not expose metadata.
As opposite to SOAP based services that has well defined formats for exposing metadata through WSDL, RESTful service endpoint doesn’t.
May be a test client has some other way to verify REST based services.
Thanks Gani for your reply!
Hi Ayaz,
I have updated this WCF article to clarify few points for most readers. Also, I have uploaded the complete code of this article.
I’ll hopefully update the next article. Part-2 (consuming article for more clarity) with source code.
Hopefully, things will be more clear after that.
Regards,
Imran
great,
Would like to have the source code.
Hi lyida,
Very soon, I’ll upload the source code for this article.
Be in touch.
Hi lyida,
As promised, I have uploaded the source code for this article along with updates for few more points. You can download the source code for WCF REST based service and use straight away as explained.
Regards,
Imran
List is getting error
Please provide details of error.
Hi chanchal,
Please use the source code of the article provided and let me know still you are facing some error.
Thanks,
Imran
i want this service to be tested with a browser guide me.
my config file giving error when i change the binding cofig to web
pls correct me.
Dear Joseph,
Please given details of error. Actually, your message has a lot of empty spaces.