Click here to Skip to main content
12,304,652 members (64,120 online)
Click here to Skip to main content
Add your own
alternative version

Stats

53.9K views
2.5K downloads
72 bookmarked
Posted

WCF RESTful service and WebGrid in ASP.NET MVC 5 - Part 1

, 27 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article we will learn how to create WCF RESTful services and consume those services in ASP.NET MVC 5 application using WebGrid Control.

Introduction

In this article we will learn how to create WCF RESTful services and consume those services in ASP.NET MVC 5 application using WebGrid Control. This is first part of the article which is having two parts. In this first part we will start by defining the terms and explaining why I picked up WCF RESTful for this demo instead of ASP.NET Web API which is de facto standard to create modern RESTful services in ASP.NET world. Then we will create demo having database (an xml file), repository and WCF RESTful service using Visual Studio 2013.

In Part 2, we will perform CRUD operations using WebGrid control which comes out of the box with ASP.NET MVC. To perform CRUD operations, controller class in ASP.NET MVC application will call to WCF service created in Part 1. The architecture of demo application will be as shown in following figure:

Architecture of demo application

Outlines

To keep the size of article reasonable, this article is divided into two parts. Contents of both articles are arranged as per following outlines:

Part 1:

  • Why WCF RESTful over ASP.NET Web API
  • Creating Project Structure
  • Creating DB and Repository
  • Creating WCF RESTful Service
  • Verifying JSON Output

Part 2:

  • Creating ASP.NET MVC 5 application
  • Displaying Data into WebGrid control
  • Adding inline Edit operation
  • Adding inline Delete operation
  • Adding Create operation

Why WCF RESTful over ASP.NET Web API

First lets start with few lines to define the terms used (and links to explore more about those as it would be helpful for beginners):

WCF: Windows Communication Foundation (WCF) is a framework for building service-oriented applications. It is used to build applications that communicate over a network, regardless of the style or protocol. Please refere to MSDN site to know more.

RESTful: RESTful is used as an adjective describing something that respects the REST constraints. REST stands for Representational State Transfer, which is a way to create, read, update or delete information on a server using simple HTTP calls. For more on REST please refer to wikipedia page.

ASP.NET Web API: ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. To learn more about Web API, please visit its home page.

Why WCF RESTful over ASP.NET Web API: To me, there are following reasons to pick WCF over Web API for this demo:

  1. WCF is used in many realtime enterprise appications as it is old and mature technology and still relevant.
  2. Web API is new and can support only HTTP client. WCF is very flexible and extendable in that term.
  3. WCF supports SOAP by default, but creating RESTful service with WCF need some extra efforts and cautions.
  4. Finally if there are new developemnt from scratch and we are sure that only HTTP support is enough we should go with Web API. But this is not the case always so it is good to learn how WCF can provide RESTful services.

Creating Project Structure

Before starting, please note the following points while following the steps given to creating demo applications:

  • Basic knowledge of WCF and ASP.NET MVC is prerequisite. We are calling database via Repository (CustomerXmlRepository class) which is based on standard Repository Pattern. This pattern is very well described at MSDN site and in this article.
  • For sake of convenience we will use xml file as a database. You can use any database as per your convenience but do the necessary change in Repository.
  • We used Visual Studio 2013 to develop attached demo code. You can use Visual Studio 2012 also but ASP.NET MVC 5 should be installed. Attached code would run fine in Visual Studio 2013 or 2012 if MVC 5 installed.
  • If you are using older version of Visual Studio you need to create similar solution and be careful for small changes due to different version.

Let us start with creating a sample of WCF RESTful service which will expose four operation contracts (methods) to perform CRUD operations.

  1. Open Visual Studio 2013 and cerate WCF service by selection “WCF Service Application” template named as “DemoWCFServiceApp” and click OK as shown in below screen shot.

    Choose Application Template for ASP.NET MVC4
     
  2. Visual Studio 2013 adds a DemoWCFServiceApp project in solution as shown below in screenshot.

    Solution Explorer
     
  3. Now we will modify DemoWCFServiceApp project solution as per our requirement. So remove existing IService1.cs and Service1.svc files then add some other files as shown below in sceenshot. We will write code in those files in further sections.

    Modified Solution Structure
     

Creating DB and Repository

  1. Under App_Data folder, open CustomerDB.xml file created in previous section and fill some data as shown below:
    <?xml version="1.0" encoding="utf-8"?>
    <customers>
      <customer>
        <id>1</id>
        <name>Jim</name>
        <address>Orlando</address>
      </customer>
      <customer>
    .......
    .......
    </customers>                        
    
  2. As you can see in Repository folder having two files ICustomerRepository.cs and CustomerXmlRepository.cs. In interface ICustomerRepository, we will declare four methods as shown below.
    interface ICustomerRepository
        {
            IEnumerable<CustomerEntity> GetAllCustomers();
            void AddCustomer(CustomerEntity customer);
            void DeleteCustomer(int id);
            void EditCustomer(CustomerEntity customer);
            int GetCustomersCount();
        }
    
  3. Now CustomerXmlRepository class will implement ICustomerRepository interface. Here we are not showing whole code written in CustomerXmlRepository since it is very simple. Please download the code and look into the code written to implement methods in CustomerXmlRepository class.
     
  4. In CustomerEntity.cs file, CustomerEntity class is decorated with [DataContract] and its properties are decorated with [DataMember] attribute. DataContractSerializer serialize public properties which are decorated with [DataMember] attribute as shown below:
    [DataContract]
    public class CustomerEntity
    {
        [DataMember]
        public int CustomerId { get; set; }
        [DataMember]
        public string CustomerName { get; set; }
        [DataMember]
        public string CustomerAddress { get; set; }
        public CustomerEntity(int id, string name, string address)
        {
            this.CustomerId = id;
            this.CustomerName = name;
            this.CustomerAddress = address;
        }
    }
    

Creating WCF RESTful Service

  1. Interface ICustomerService is a ServiceContract which describes what a service can expose to the outside world. When we implement WCF RESTful service, we have to use HTTP verbs like GET, POST, PUT and DELETE. WebGet method is used for GET verb only and WebInvoke method is used for POST, PUT and DELETE. Following is the code which we need to write in ICustomerService.cs :
    [ServiceContract]
    public interface ICustomerService
    {
        // WebGet attribute is used to make GET request in WCF REST service
        [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllCustomers")]
        IEnumerable<CustomerEntity> GetAllCustomers();
    
        // WebInvoke attribute is used to make POST, DELETE and PUT request in WCF REST service
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST", UriTemplate = "AddCustomer")]
        void AddCustomer(CustomerEntity customer);
    
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "DELETE", UriTemplate = "DeleteCustomer")]
        void DeleteCustomer(int id);
    
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "PUT", UriTemplate = "EditCustomer")]
        void EditCustomer(CustomerEntity customer);
    
        [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetCustomersCount")]
        int GetCustomersCount();
    }
    
  2. CustomerService will implement ICustomerService contract. Here we are using constructor base dependency Injection. Dependency Injection helps writing decoupled code. For more information about Dependency Injection Visit here. CustomerService class looks like:

    Service Class
     
  3. Finally we will configure endpoints of this service. Endpoint of a service explain three things as follows:
     
    1. Address: It defines "WHERE". Address is the URL that detects the location of the service.
    2. Binding: It defines "HOW". Binding defines how the service can be accessed. In our case we are using "webHttpBinding".
    3. Contract: It defines "WHAT". Contract identifies what should be exposed by the service. Our service exposing "DemoWCFServiceApp.ICustomerService" to the clients.


    Following is the code from Web.config defining the endpoints for our service:
     <services>
      <service name="DemoWCFServiceApp.CustomerService">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="DemoWCFServiceApp.ICustomerService" />
      </service>

Note: Now we can configure the services to multiple endpoints having their own Addresses, Behaviors and Contracts. It you are interested in exposing same service to RESTful and SOAP clients, please look at discussion here on stackoverflow and this article. here on stackoverflow and this article.

Verifying JSON Output

Run the service and to test open a browser and enter the URL: http://localhost:1786/CustomerService.svc/GetAllCustomers in address bar. Hope you will be able to see data in JSON format as shown below in screenshot.

HTML Layout of Views

I have used Google Chrome browser but you may be using different browser but key point is that you must be able to get JSON. Depending upon browser may see JSON data in different format or file would be downloaded having JSON data which you can view with notepad. One more thing while clicking on run button in Visual Studio if the focus is on .svc file then “WCF Test Client” window will open otherwise selected browser would open. In both the case service would be running and up.

Conclusion

In this article we learned how to create a WCF RESTful service with Visual Studio 2013. In next part we will create a ASP.NET MVC 5 application which will have a WebGrid control. For CRUD operation MVC application will call to the WCF series we just created. Your comments and suggestions are most welcome. Thanks.

License

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

Share

About the Author

Snesh Prajapati
Software Developer
India India
I am a Software Developer working on Microsoft technologies. My interest is exploring and sharing the awesomeness of emerging technologies.

You may also be interested in...

Comments and Discussions

 
GeneralAwesome Post! Pin
sameer_s8-Sep-15 2:31
membersameer_s8-Sep-15 2:31 
AnswerRe: Awesome Post! Pin
Snesh Prajapati8-Sep-15 5:54
mvpSnesh Prajapati8-Sep-15 5:54 
GeneralRe: Awesome Post! Pin
sameer_s8-Sep-15 6:45
membersameer_s8-Sep-15 6:45 
AnswerRe: Awesome Post! Pin
Snesh Prajapati8-Sep-15 15:25
mvpSnesh Prajapati8-Sep-15 15:25 
QuestionMessage Automatically Removed Pin
31-Aug-15 17:32
memberMember 1194905831-Aug-15 17:32 
QuestionGreat Article Pin
Member 115105929-Mar-15 10:07
memberMember 115105929-Mar-15 10:07 
QuestionMessage Removed Pin
marcio_ordonez30-Dec-14 3:57
membermarcio_ordonez30-Dec-14 3:57 
AnswerRe: Where is part 2? Pin
Snesh Prajapati30-Dec-14 4:46
professionalSnesh Prajapati30-Dec-14 4:46 
GeneralRe: Where is part 2? Pin
marcio_ordonez30-Dec-14 5:14
membermarcio_ordonez30-Dec-14 5:14 
AnswerRe: Where is part 2? Pin
Snesh Prajapati30-Dec-14 5:37
professionalSnesh Prajapati30-Dec-14 5:37 
GeneralGreat article for beginner Pin
Yogendra Gupta8-Nov-14 0:13
memberYogendra Gupta8-Nov-14 0:13 
AnswerRe: Great article for beginner Pin
Snesh Prajapati8-Nov-14 3:43
professionalSnesh Prajapati8-Nov-14 3:43 
GeneralMessage Removed Pin
Binu19853-Nov-14 23:01
memberBinu19853-Nov-14 23:01 
AnswerRe: Nice article.... Pin
Snesh Prajapati4-Nov-14 16:44
professionalSnesh Prajapati4-Nov-14 16:44 
QuestionNice article but missed behavior Pin
ssathy6214-Oct-14 5:28
memberssathy6214-Oct-14 5:28 
AnswerRe: Nice article but missed behavior Pin
Snesh Prajapati14-Oct-14 18:16
professionalSnesh Prajapati14-Oct-14 18:16 
Questioni am getting error like"The message with To 'http://localhost:8245/Customerservice.svc/getallcustomers' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddr Pin
Member 1109960724-Sep-14 9:25
memberMember 1109960724-Sep-14 9:25 
AnswerRe: i am getting error like"The message with To 'http://localhost:8245/Customerservice.svc/getallcustomers' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's Endpoint Pin
Snesh Prajapati24-Sep-14 17:30
professionalSnesh Prajapati24-Sep-14 17:30 
QuestionTesting the WCF Restful Services Pin
c_4less14-Jul-14 6:15
memberc_4less14-Jul-14 6:15 
AnswerRe: Testing the WCF Restful Services Pin
Snesh Prajapati14-Jul-14 22:17
professionalSnesh Prajapati14-Jul-14 22:17 
GeneralRe: Testing the WCF Restful Services Pin
c_4less15-Jul-14 6:02
memberc_4less15-Jul-14 6:02 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun26-Jun-14 19:38
memberHumayun Kabir Mamun26-Jun-14 19:38 
GeneralMy vote of 5 Pin
Volynsky Alex26-Jun-14 7:15
professionalVolynsky Alex26-Jun-14 7:15 
AnswerRe: My vote of 5 Pin
Snesh Prajapati26-Jun-14 17:07
professionalSnesh Prajapati26-Jun-14 17:07 
GeneralRe: My vote of 5 Pin
Volynsky Alex26-Jun-14 21:44
professionalVolynsky Alex26-Jun-14 21:44 
QuestionMy vote of 5... Pin
Yogesh Kumar Tyagi25-Jun-14 18:21
professionalYogesh Kumar Tyagi25-Jun-14 18:21 
AnswerRe: My vote of 5... Pin
Snesh Prajapati25-Jun-14 18:32
professionalSnesh Prajapati25-Jun-14 18:32 
GeneralRe: My vote of 5... Pin
Yogesh Kumar Tyagi25-Jun-14 19:20
professionalYogesh Kumar Tyagi25-Jun-14 19:20 
AnswerRe: My vote of 5... Pin
Snesh Prajapati25-Jun-14 19:29
professionalSnesh Prajapati25-Jun-14 19:29 
GeneralRe: My vote of 5... Pin
Yogesh Kumar Tyagi25-Jun-14 19:45
professionalYogesh Kumar Tyagi25-Jun-14 19:45 
Questionwooooooooow Pin
aqie1322-Jun-14 16:57
memberaqie1322-Jun-14 16:57 
AnswerRe: wooooooooow Pin
Snesh Prajapati22-Jun-14 19:01
professionalSnesh Prajapati22-Jun-14 19:01 
GeneralGreat Article Pin
Mahsa Hassankashi22-Jun-14 7:26
memberMahsa Hassankashi22-Jun-14 7:26 
AnswerRe: Great Article Pin
Snesh Prajapati22-Jun-14 15:32
professionalSnesh Prajapati22-Jun-14 15:32 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160530.1 | Last Updated 27 Jun 2014
Article Copyright 2014 by Snesh Prajapati
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid