Blog Archives

Consuming WCF REST service

Update :  We can consume the WebApi services also in the same way using the code below. To read about Asp.Net WebApi services refer to my post

In my last post ( http://wp.me/p1hH3Q-20 ) i have shown how to create a basic REST enabled service using WCF.

Here i am going to discuss how to consume your REST service. There are couple of ways we can consume the service but i am taking an approach using WebClient.

To understand the WCF service structure i am trying to consume please have a look at  http://wp.me/p1hH3Q-20


using System;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.Services;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Net;
using System.Runtime.Serialization.Json;

<strong>// GET request</strong>
 {
 <strong>WebClient proxy = new WebClient();</strong>

//DownloadData sends data to server using the specific URI defined for your webmethod.
 byte[] data = proxy.<strong>DownloadData</strong>("http://localhost:3971/Service1.svc/GetEmployees");

 Stream stream = new MemoryStream(data);

// serializing the returned type which is Employee[]
 DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(Employee[]));
 var arrEmp = obj.ReadObject(stream) as Employee[];
 gvEmployees.DataSource = arrEmp as Employee[];
 gvEmployees.DataBind();
 }

</pre>
<strong>// POST request</strong>
 {

Employee newItem = new Employee() { EmployeeID = "112", Name = "Prasdjf", Email = "test@tes.com" };
 WebClient proxy = new WebClient();
 proxy.Headers["Content-type"] = "application/json";
 MemoryStream ms = new MemoryStream();

//serialize the input parameter

DataContractJsonSerializer serializerToUpload = new DataContractJsonSerializer(typeof(Employee));

serializerToUpload.WriteObject(ms, newItem);

// upload the data to call AddEmployee web method which returns Employee object.
 byte[] data = proxy.UploadData("http://localhost:3971/Service1.svc/AddEmployee", "POST", ms.ToArray());
 Stream stream = new MemoryStream(data);
// serialize the returned type
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(Employee));

// read the returned type as Employee

var resultSampleItem = obj.ReadObject(stream) as Employee;
 Response.Write(resultSampleItem.EmployeeID + " => " + resultSampleItem.Name + " => " +
 resultSampleItem.Email);
<pre>}

Things to note:
1. There is no need to add any web reference to our service as all web methods are available as URI.
2. DataContractJsonSerializer is really helpful if your response format is Json. JSON is the lightest data format accepted by almost all the parties. XML is also supported.
3. There are other approaches too, using HttpWebRequest/HttpWebResponse is another way of doing it.
Consuming REST web service by Jquery $.ajax method.
Here is a jquery call to GetEmployeeDetails webmethod to a wcf service. Method signature is like below

</pre>
[OperationContract]
 [WebInvoke(Method = "POST", UriTemplate = "/GetEmployeeDetails/{EmployeeID}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
 Employee GetEmployeeDetails(string EmployeeID);
<pre>

Notice the URL http://localhost:3971/Service1.svc/GetEmployeeDetails/54543 which has input parameter in the last. it depends on how URI is defined for our webmethod.

</pre>
<script type="text/javascript">
 var Type = "POST";
 var Url = "http://localhost:3971/Service1.svc/GetEmployeeDetails/54543";
 var Data = {};
 var ContentType = "application/json;charset=utf-8";
 var DataType = "json";
 var ProcessData = false;
 var method = "GetEmployeeDetails";

$("#btnCallRest").click(function () {

// to enable cross - site scripting
jQuery.support.cors = true;
 $.ajax({
 type: Type, //GET or POST or PUT or DELETE verb
 url: Url, // Location of the service
 data: Data, //Data sent to server
 contentType: ContentType, // content type sent to server
 dataType: DataType, //Expected data format from server
 processdata: ProcessData, //True or False
 success: function (result) {//On Successfull service call
 ServiceSucceeded(result);
 },
 error: ServiceFailed// When Service call fails
 });

});

function ServiceFailed(result) {
 alert('Service call failed: ' + result.status + '' + result.statusText);
 Type = null;
 Url = null;
 Data = null;
 ContentType = null;
 DataType = null;
 ProcessData = null;
 }

function ServiceSucceeded(result) {
 if (DataType == "json") {
 if (method == "GetEmployeeDetails") {
 alert(' ID :'+ result.EmployeeID + '\n Name:' + result.Name + '\n Email : ' + result.Email);
 }
 else {
 resultObject = result.GetEmployeeResult;
 var string = result.EmployeeID + " \n " + result.Name + " \n " + result.Email;
 alert(string);
 }
 }
 }
<pre>

That’s it! we are good to go.
Hope it helps!!

Advertisements