WCF Restful Service Implementation - .Net Framework 4.0

random

WCF Restful Service Implementation - .Net Framework 4.0

How to Create RESTful WCF Service API - ASP.Net


In my previous article I explained about Web Service in ASP.net, Register WCF Service with IIS and ASP Dot Net, About WCF - An Introduction with Example and many more. 

In this article we will learn how to implement RestFul WCF Services in ASP .Net with XML and JSON returns data. RESTful Service are those which follow Representational State Transfer architectural style. A WCF service allows us to make calls and exchange messages using SOAP over a variety of protocols like HTTP, TCP, Named Pipes and MSMQ etc. 

RESTful architecture use HTTP for all CRUD operations like (Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE). It’s simple as well as lightweight. 

For example I will implement only a GET request and it will return certain types of data (i.e. Customer details) in XML and JSON format. We are just utilizing HTTP as a transport. 

There are following steps to create a Restful service :-
  1. Create a WCF Service Application.
  2. Preparing the data (e.g. Customers) to return.
  3. Creating Service Contract
  4. Implementing Service.
  5. Configure Service and Behavior
Step 1. Create a WCF Service Application
  • Open Visual Studio 2010.
  • From File -> New Project. Select WCF from left and create a new WCF Service Application.





Step 2. Preparing the data to return
  • Now add a class to newly created project. Name it to Customers.cs. Now this Customers.cs file will contain two things. First one is Data Contract. Second one is a singleton implemented class that gets Customers data from a database and return list of Customers. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;

namespace Create_Restful_WCF_Service
{
    [DataContract]
    public class Customer
    {
        [DataMember]
        public int CustomerId { get; set; }
        [DataMember]
        public string CustomerName { get; set; }
        [DataMember]
        public string CustomerAddress { get; set; }
    }

    public partial class Customers
    {
        private static readonly Customers _obj = new Customers();
        private Customers() { }

        public static Customers Instance
        {
            get
            {
                return _obj;
            }
        }

        public List<Customer> CustomerList
        {
            get
            {
                return customers;
            }
        }

        private List<Customer> customers = new List<Customer>()
        {
         new Customer() { CustomerId = 1, CustomerName = "Dell", CustomerAddress = "Banglore"},
         new Customer() { CustomerId = 2, CustomerName = "Sony", CustomerAddress = "New Delhi"},
         new Customer() { CustomerId = 1, CustomerName = "Apple", CustomerAddress = "USA"},
         new Customer() { CustomerId = 1, CustomerName = "Samsung", CustomerAddress = "China"},
         new Customer() { CustomerId = 1, CustomerName = "Micromax", CustomerAddress = "New Delhi"}
         };
    }
}

Step 3. Creating Service Contract
  • Now add a new WCF Service to this project as follows: It will add contract as well as service file to project. Following is the code for service contract i.e. ICreate_Restful_WCF_Service.cs.
WCF Restful Service Implementation - Net Framework 4.0

[ServiceContract]
    public interface ICreate_Restful_WCF_Service
    {
        // XML format only
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetCustomerListXML")]
        List<Customer> GetCustomerListXML();

        // JSON format only
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetCustomerListJSON")]
        List<Customer> GetCustomerListJSON();
    }

ICreate_Restful_WCF_Service contains only two methods i.e. GetCustomerListXML, GetCustomerListJSON. Important points to understand about these methods are WebInvoke attribute parameters. 
  • Method = "GET", represents an HTTP GET request.
  • ResponseFormat = WebMessageFormat.Xml, response format will be XML here but we can return JSON as well by changing its value to WebMessageFormat.Json.
  • BodyStyle = WebMessageBodyStyle.Wrapped, indicates both the request and response are wrapped.
  • UriTemplate = "GetCustomerList/", it has two parts, URL path and query.

Note: Don't forget to add using System.ServiceModel.Web namespace.

Step 4. Implementing RESTful Service
  • In this step we are going to implement the service. Only two methods GetCustomerListXML, GetCustomerListJSON are defined in the contract, so implementing service class will be as follows:

public class Create_Restful_WCF_Service : ICreate_Restful_WCF_Service
    {
        public List<Customer> GetCustomerListXML()
        {
            return Customers.Instance.CustomerList;
        }

        public List<Customer> GetCustomerListJSON()
        {
            return Customers.Instance.CustomerList;
        }
    }

Step 5. Configure Service and Behavior
  • The last step is to configure the service and its behaviors using the configuration file. Following is the complete ServiceModel configuration settings.
<system.serviceModel>
    <services>
      <service name="Create_Restful_WCF_Service.Create_Restful_WCF_Service" behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="Create_Restful_WCF_Service.ICreate_Restful_WCF_Service" behaviorConfiguration="web"></endpoint>
        <endpoint address="soap" contract="Create_Restful_WCF_Service.ICreate_Restful_WCF_Service" binding="basicHttpBinding"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

webHTTPBinding is the binding used for RESTful services. Now our Resful service is done. Run the WCF Service Application and test it.


Demo


WCF REST response in XML 


WCF REST response in XML format


WCF REST response in JSON format

WCF REST response in JSON format

Download the source code click here

WCF Restful Service Implementation - .Net Framework 4.0 Reviewed by Ravi Kumar on 4:46 PM Rating: 5

No comments:

All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form

Name

Email *

Message *

Powered by Blogger.