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 ( ) 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

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[];

<strong>// POST request</strong>

Employee newItem = new Employee() { EmployeeID = "112", Name = "Prasdjf", Email = "" };
 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 + " => " +

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

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

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.

<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 = true;
 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
 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;

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


About saxenapraveen

I have 14 years of experience in enterprise software development,designing and leading team to provide reliable and scalable solutions for cloud and device ready businesses.

Posted on February 14, 2012, in .NET, WCF and tagged , , , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: