CRUD Operations using WCF RESTful Service – Part 1

By | January 8, 2014

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

MCSD Exam: 70-487Let’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.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”.DataContract in WCF

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

  • 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:

IBookRepository for WCF Service

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.

[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.
[/su_table]

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“.Add New WCF REST Service

It will add two new files to project:

  1. IBookService.cs
  2. BookService.svc

Following is the code for WCF Service Contract i.e. IBookService:WCF Service Contract Interface
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.
Implementation code of BookService for all operations is as follows:WCF RESTful Service CRUD
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
  • 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:CRUD REST based Service

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

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.
  • 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.WCF RESTful Running Service
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:Books REST Service results
As you can see that we modify the browser URL with “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:JSON Output for REST Service
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/
  • 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:REST Service XML Output
Now, lets move to Part-2 of this WCF tutorial series, we will consume all these operations.

18 thoughts on “CRUD Operations using WCF RESTful Service – Part 1

  1. Diastowo Faryduana

    did you try the PUT and POST method? it didn’t work.. can you tell us to make it right? thanks

  2. nevil

    HI,

    whenver i change PUT to POST..it doesnt work…Please suggest.

    Thanks.

  3. Frankie

    Hi,

    How can I add authentication(ie, username and password) into the project?

    Thanks.

    1. WebdevTutorial

      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

  4. Ayaz Mahapule

    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

    1. WebdevTutorial

      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.

        1. WebdevTutorial

          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

  5. Iyida Johnson

    great,
    Would like to have the source code.

    1. WebdevTutorial

      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

    1. WebdevTutorial

      Hi chanchal,

      Please use the source code of the article provided and let me know still you are facing some error.

      Thanks,
      Imran

  6. Connors Joseph

    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.

Comments are closed.