1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

WCF RESTful Services

Discussion in 'ASP.NET' started by MinalS, Feb 8, 2015.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    31
    Trophy Points:
    0
    The RESTFUL service used the HTTP protocol for performing the CRUD operations. The architecture focuses on the concepts of the distributed system as statelessness, caching, etc. It provides advantages like interoperability, scalability, efficiency, performance, etc.

    The HTTP protocol is useful for communication between the resources over the web. There are several methods to communicate with the resources. They are as explained below:
    1. POST: It states that the data to be processed by the identified resource.
    2. DELETE: It is useful for deleting the resource.
    3. GET: It is used for requesting the representation of the resource.
    4. PUT: It is useful for creating or updating the resource.
    5. OPTIONS: It is used for returning the methods supported by the resource.
    6. HEAD: It is used for retrieving only the header of the resource.
    Let’s create a RESTFUL service in WCF for returning XML data.
    1. Open the Visual Studio application in your system.
    2. Click ‘File’, ‘New Project’, select the ‘WCF Service Application’ option from the left pane.

      [​IMG]
    3. Right click on the project in the solution explorer window, click ‘Add’, ‘Class’ from the list. Save as ‘Student.cs’

      [​IMG]
    4. In the Student.cs file, add the following code.

      Code:
      
      [ DataContract ]
      public class Student
      {
      	[DataMember]
      	public int StudentID{ get; set; }
      	[DataMember]
      	public string StudName{ get; set; }
      	[DataMember]
      	public int Marks{ get; set; }
      }
      
      
    5. In the singleton class, add the following code.

      Code:
      
      public partial class Student
      {
      	private static readonly Students_instance = new Students();
      	private Students() { }
      	public static Students Instance
      	{
      		get
      		{
      			return _instance;
      		}
      	}
      	public List StudentList
      	{
      		get
      		{
      			return students;
      		}
      	}
      	private List<Student>students = new List<Student>()
      	{
      		new Student() { StudentID = 101, StudName = “Amit”, Marks = 90 },
      		new Student() { StudentID = 102, StudName = “Nick”, Marks = 50 },
      		new Student() { StudentID = 103, StudName = “Hardik”, Marks = 95 },
      	};
      }
      
    6. Add the WCF Service to the existing project. A service file and contract is added.
    7. In the service contract file add the following code.
      Code:
      using System.ServiceModel.Web;
      
      [ServiceContract]
      public interface IStudentRESTService
      {
      	[OperationContract]
      	[WebInvoke (Method =”GET”, ResponseFormat = WebMessageFormat.Xml, 
      	BodyStyle = WebMessageFormat.Xml,
      	UriTemplate = “GetStudentList/”) ]
      	
      	List GetStudentList();
      }
      
    8. Implement the service by adding the code mentioned below:
      Code:
      public class StudentRESTService : IStudentRESTService
      {
      	public List GetStudentList()
      	{
      		return Students.Instance.StudentList;
      	}
      }
      
      
    9. In the configuration file of the service, add the following code.
      Code:
      <system.ServiceModel>
      	<services>
      	<service name = “MyRESTService.StudentRESTService” behaviorConfiguration=”serviceBehavior”>
      		<endpoint address = “ “ binding = “webHttpBinding” contract = “MyRESTService.IStudentRESTService” behaviorConfiguration=”web” >
      		</endpoint>
      	</service>
      	</services>
      	<behaviors>
      		<serviceBehaviors>
      		<behavior name = “serviceBehavior”>
      			<serviceMetadata httpGetEnabled = “true” />
      			<serviceDebug includeExceptionDetailInFaults=”false” />
      		</behavior>
      		</serviceBehaviors>
      		<endpointBehaviors>
      			<behavior name = “web” >
      			<webHttp/>
      			</behavior>
      		</endpointBehaviors>
      	</behaviors>	
      	<serviceHostingEnviornment multipleSiteBindingEnabled = “true” />
      </system.ServiceModel>
      

    CRUD operations on WCF Restful Services



    User uses the standard HTTP verbs for the CRUD verbs Create, Update, Delete operations. The following code represents the data contact class Order.

    Code:
    
    [ DataContract ]
    public class Order
    {
    	[ DataMember ] 
    	public int OrderID;
    	[ DataMember ]
    	public string ProductName;
    	[ DataMember ] 
    	public string location;
    }
    
    
    1. Create an interface IOrderDetails and class OrderDetails as mentioned below:
      Code:
      public interface IOrderDetails
      {
      	List GetAllData();
      	Order GetOrderByID( int id);
      	Order AddNewOrder(Order item);
      	bool DeleteOrder( int id );
      	bool UpdateOrder( Order item );
      }
      
      public class OrderDetails : IOrderDetails 
      {
      	private List <Order> orders = new List <Order>();
      	private int counter = 1;
      	
      	public OrderDetails()
      	{
      		AddNewOrder ( new Order { ProductName = “Pen”, location=”India”});
      		AddNewOrder ( new Order { ProductName = “Laptop”, location=”UK”});
      		AddNewOrder ( new Order { ProductName = “IPad”, location=”USA”});
      	}
      	//retrieving all the data
      	public List GetAllData()
      	{
      		return orders;
      	}
      
      	//retrieve the data using ID
      	public Order GetOrderByID(int id)
      	{
      	 	return orders.Find( o => o.id ==id );
      	}
      
      	//updating the data
      	public bool UpdateOrder( Order Orderupdated )
      	{
      		if(Orderupdated == null )
      		throw new ArgumentNullException (“Orderupdated”);
      		
      		int ix = orders.FindIndex(o =>o.id == Orderupdated.id );
      		if( ix == - 1)
      			return false;
      		orders.RemoveAt (ix);
      		orders.Add(Orderupdated);
      		return true;
      	}
      
      	//deleting the data
      	public bool DeleteOrder ( int id )
      	{
      		int ix = orders.FindIndex ( o => o.id = id )
      		if( ix == -1 )
      		return false;
      	
      		orders.RemoveAll ( o=>o.id == id)
      		return true;
      	}
      }
      
    2. Add the following code WCF service contract in the service as mentioned below:
      Code:
      [ ServiceContract ]
      public interface IOrderService
      {
      	[ OperationContract ]
      	[ WebInvoke ( Method = “GET”, RequestFormat = WebMessageFormat.Json, 
      	ResponseFormat = WebMessageFormat.Json, UriTemplate = “Orders/” ) ]
      	List GetOrderList();
      
      	[ OperationContract ]
      	[ WebInvoke ( Method = “GET”, RequestFormat = WebMessageFormat.Json, 
      	ResponseFormat = WebMessageFormat.Json, UriTemplate = “OrdersById/{id}”)]
      	Order GetOrderById( string id );
      	
      	[ OperationContract ]
      	[ WebInvoke ( Method = “PUT”, RequestFormat = WebMessageFormat.Json, 
      	ResponseFormat = WebMessageFormat.Json, UriTemplate = “AddOrder/{id}/” ) ]
      	string AddOrder(Order order, string id );
      	
      	[OperationContract]
      	[ WebInvoke ( Method = “PUT”, RequestFormat = WebMessageFormat.Json, 
      ResponseFormat = WebMessageFormat.Json, UriTemplate = “UpdateOrder/{id}/” ) ]
      	string UpdateOrder ( Order order, string id );
      	
      	[OperationContract]
       WebInvoke ( Method = “DELETE”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = “DeleteOrder/{id}/” ) ]
      	string DeleteOrder( string id );
      }
      
    3. The WebInvoke attribute is added in the above code. The HTTP verbs are used.
      1. Method: It is used for the specific action on the code.
      2. RequestFormat: It is the request message format. It can be JSON, XML, etc.
      3. ResponseFormat: It is the response format for the code.
      4. UriTemplate: It is the unique URI for each specific service operations.
    4. The implementation of the OrderService for the above operations is as mentioned below:
      Code:
      public class OrderService: IOrderService
      {
      	static IOrderDetails details = new OrderDetails();
      	public List GetOrderList()
      	{
      		return details.GetAllData();
      	}
      	public Order GetOrderByID( int id)
      	{
      		return details.GetOrderById ( int.Parse(id));
      	}
      	 
      	public string AddOrder( Order order, string id)
      	{
      		Order newOrder = details.AddNewOrder( item);
      		return “id” + newOrder.Orderid;
      	}
      	public string UpdateOrder( Order order, string id)
      	{
      		bool updated = details.UpdateOrder(item);
      		if(updated)
      			return “Order id is=”+id;
      		else
      			return “Not able to update the order”;
      	}
      	public string DeleteOrder( string id)
      	{
      		bool deleted = details.DeleteOrder(int.Parse(id));
      		if(deleted)
      			return “Order id=”+id;
      		else
      			return “Not able to delete the order”;
      	}
      
      }
      
    5. In the configuration file in the <system.serviceModel> tag add the following code.
      Code:
      <system.serviceModel>
      	<services>
      <service name = “RESTserviceCRUD.OrderService” behaviorConfiguration=”serviceBehavior” >
      <endpoint address =” “ binding=”webHttpBinding” contract=”RESTServiceCRUD.IOrderService” behaviorConfiguration=”RESTEndpointBehavior” >
      		</endpoint>
      		</service>
      	</services>
      	<behavior>
      		<endpointBehaviors>
      			<behavior name=”RESTEndpointBehavior”>
      			<webHttp/>
      			</behavior>
      		</endpointBehaviors>
      		<serviceBehaviors>
      			<behavior name=”serviceBehavior”>
      			<serviceMetadata httpGetEnabled=”true” />
      			<seviceDebug includeExceptionDetailInFaults=”false” />
      		</serviceBehaviors>
      	</behavior>
      </system.serviceModel>
      

    Consuming the WCF RESTful service



    In WCF RESTful service, the jQuery code for all the CRUD operations against the service. The service can be consumed by several client applications.

    The function that makes call to the RESTful web service for collecting all data.
    Code:
    function GetAllData()
    {
    	$.ajax ( {
    	type: “GET”, 
    	url: “http://localhost/RESTServiceCRUD/OrderService.svc /Order/”,
    	contentType: ”json”,
    	dataType: “json”,
    	success: function (data)
    	{
    		$each( data, function (key, value )
    		{
    			var jsonData = JSON.stringify ( value );
    			var objData = $.parseJSON (jsonData);
    			var orderid = objData.OrderID;
    			var productname = objData.ProductName;
    			var location = objData.Location;
    			$ ( ‘ ‘ + orderid + ‘ ‘ + productname + ‘ ‘ + location+ ‘ ‘ ) .appendTo(‘#Orders’);
    			
    		} );
    	}
    }
    

    Error Handling in WCF RESTful service



    The error handling is supported by the WCF for the HTTP services. User can easily return the HTTP status code to the user. The code takes OrderID as an input and returns the Order object in JSON format.

    For retrieving the HTTP status code, the following implementation is as mentioned below:

    Code:
    
    public Order GetOrderById ( string id )
    {
    	Order order = details.GetOrderById ( int.Parse( id ) );
    	if ( order == null )
    	{
    		throw new webFaultException ( HttpStatusCode.NotFound ) ;
    	}
    	return order;
    }
    
    
    If user wants to add the custom details with the error code, the user defined type containing the data is defined. The code for the service method is as mentioned below:

    Code:
    
    public Order GetOrderById ( string id )
    {
    	Order order = details.GetOrderById ( int.Parse( id) );
    	if ( order = = null )
    	{
    MyCustomErrorDetail customError = new MyCustomErrorDetail ( “Order not found”);
    throw new WebFaultException ( customError, HttpStatusCode.NotFound);
    	}
    	return order;
    }
    
    
     
    Last edited by a moderator: Jan 21, 2017

Share This Page