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:
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:
- WCF is used in many realtime enterprise appications as it is old and mature technology and still relevant.
- Web API is new and can support only HTTP client. WCF is very flexible and extendable in that term.
- WCF supports SOAP by default, but creating RESTful service with WCF need some extra efforts and cautions.
- 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.
- 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.
- Visual Studio 2013 adds a DemoWCFServiceApp project in solution as shown below in screenshot.
- 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.
Creating DB and Repository
- 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>
- 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();
}
- 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.
- 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
- 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(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllCustomers")]
IEnumerable<CustomerEntity> GetAllCustomers();
[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();
}
- 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:
- Finally we will configure endpoints of this service. Endpoint of a service explain three things as follows:
- Address: It defines "WHERE". Address is the URL that detects the location of the service.
- Binding: It defines "HOW". Binding defines how the service can be accessed. In our case we are using "webHttpBinding".
- 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>
</services>
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.
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.