Category Archives: WCF

WebApi – Asp.Net “ROUTE” to “REST”

WHAT: Webapi is a framework to build Http services that uses standard https verbs like GET, POST, PUT and DELETE to achieve data operations. WCF already had a way (i didn’t like it though ūüôā )¬†to achieve this but there were things that developers may find cumbersome. Few of them are as mentioned below

  1. Web browsers need to do a lot of XML parsing and DOM manipulation for SOAP based services.
  2. Only WebHttpBinding supports http services and those configuration settings were really painful (at least for me).

“WebApi framework pretty much¬†utilizes existing Asp.Net routing framework which comes with framework 4.0”

WHY: Suddenly there is a huge demand of making our web applications available on different platforms/devices like mobiles,smart phones,tablets etc. Http services help us to provide seemless integration to our data access methodologies across all the platforms. One service for all devices and platform.

WHERE: It comes in-built with Asp.Net MVC 4.0 framwork. you can download it from¬†. Though WebApi implementation (which I am using)¬†is not limited to MVC. Webforms can also enjoy the “Route to REST” :).

You should have Fiddler tool to¬†see how it works. Download it from¬†it is a web debugger proxy tool. You can simulate http calls using this tool. It won’t be necessary in my example though.

HOW:¬† Once you install MVC 4.0, you will notice a new project template called WebApi. It will give you basic methods and a working sample created for you. Though i would prefer to use “Empty” project type because as a beginner i wanted to see how it works.

  • Install MVC4.0
  • Open new project in VS 2010.
  • select Asp.Net MVC 4 web application.
  • Choose “Empty” project.
  • goto project properties -> Web -> StartAction -> Specific Page -> give “employees/”
  • assign a port like 9090
  • Global.asax.cs : Add the new namespaces mentioned in code. Now we need to define a route format¬†which we would use to access the endpoints which in our case is an action method.
using System.Web.Http;
using System.Web.Routing;
protected void Application_Start(object sender, EventArgs e)
new {id = RouteParameter.Optional  });
  • this route defines that you can access this service by browing either http://localhost:9090/employees or http://localhost:9090/employees/1 . what it means is that for Get requests Id is¬†optional. When we don’t pass id we will get all employees¬†and if Id is specified you get only Employee with the same ID.
  • If you want to allow method names in url just need to modify your Route in Global.asax with¬†“{controller}/{action}/id”. it will allow your web methods to be accessed as resources.
  • Add “Employee” class with public ID and Name properties.

Add a controller name it “EmployeesController”. and paste the below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http;
using System.Net.Http.Headers;
namespace WebApiDemo.Controllers
public class EmployeesController : ApiController
static List<Employee> _employees = InitEmployeeCollection();
private static List<Employee> InitEmployeeCollection()
var empList = new List<Employee>();
empList.Add(new Employee { ID = 0, Name = "Praveen" });
empList.Add(new Employee { ID = 1, Name = "Narsi" });
empList.Add(new Employee { ID = 2, Name = "Ganesh" });
empList.Add(new Employee { ID = 3, Name = "Venu" });
return empList;


public IEnumerable<Employee> Get()
return _employees;

public Employee Get(int id)
var emp = (from e in _employees where e.ID == id
select e).FirstOrDefault();

if (emp == null)
//HttpResponseMessage is part .net 4.5
//return type should be HttpResponseMessage<Employee>
//var foundEmp = new HttpResponseMessage<Employee>(HttpStatusCode.NotFound );
// return httpstatuscode.notfound =  404
return emp;

// insert
public  Employee Post(Employee newEmployee)
newEmployee.ID  = _employees.Count() + 1;
_employees.Add(newEmployee );
//if success
//var foundEmp = new HttpResponseMessage<Employee>(HttpStatusCode.Created );
//return httpstatuscode.created i.e.  201
return newEmployee;

public Employee Put(Employee emp)
var changedEmp = (from e in _employees
where e.ID == emp.ID
select e).FirstOrDefault();
changedEmp.Name = emp.Name;
return changedEmp;

public void Delete(Employee empToDelete)


Please notice that name of controller methods are named as Get(),Post(),Put() and Delete(). These are pretty much like http verbs and your framwork is able to understand the kind of http action user is trying for just by these names itself . You can also name it like GetEmployee() etc. You can also keep other names but then we have to map it with URI (not covered in this post).Code is nothing new, plain CRUD operations.

  • Build the application and try to run. you would see it hits http://localhost:9090/employees/¬† as you have mentioned this starting point in project properties. It will not render anything but it will try to open a file (use notepad) which willl contain Json format output.
  • There is no Id specified in the url so it takes you to Get() method.
  • which returns the employee list but in Json format. to read about Json in this context refer to my post on Json¬†.
  • if you type http://localhost:9090/employees/1¬† it will return employee id and ¬†name with id equal to 1. It will hit overloaded Get method with Id as parameter which will return Employee object in json format.

Now , your service is in place and you have tested using urls of course only Get verbs. To test Post and other requests you can use fiddler or developer tools (press F12).

Step by step instructions to use developer tools and basic tutorial is also available on MVC official website .

Now to consume this webservice as it is. you can read my post on consuming REST services you just need to change URI where your service is hosted.

Otherwise you can use this class to consume the service.

<pre>using System.Web.Services;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Net;
using System.Runtime.Serialization.Json;
public class ConsumerClient
public static List<Employee> Get()
WebClient proxy = new WebClient();
//DownloadData sends data to server using the specific URI defined for your webmethod.
byte[] data = proxy.DownloadData("http://localhost:9090/Employees/");
Stream stream = new MemoryStream(data);
// serializing the returned type which is Employee[]
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Employee>));
var lstEmp = obj.ReadObject(stream) as List<Employee>;

return lstEmp;


public static Employee Post(Employee emp)
Employee newItem = new Employee() { ID = 0, Name = emp.Name };
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:9090/Employees", "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 newEmployee = obj.ReadObject(stream) as Employee;
return newEmployee;

Above deserialization method is inbuilt with Dot net framework 4.0 though there are few other libraries which helps you deserialize the
json objects in an easier way. one of the best one i found is JSON.Net which is really easy to understand.
To read more on this please refer to My post on Json.Net .

I hope it helps you to start.
All the best!!


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!!

WCF REST service – part 1

REST (Representational State Transfer) has emerged in the last few years alone as a predominant Web service design model. In fact, REST has had such a large impact on the Web that it has mostly displaced SOAP- and WSDL-based interface design because it’s a considerably simpler style to use.
But i am not going to talk about SOAP Vs REST. This post only describes how to implement REST web services usinf WCF model. Again WCF is just another way of implement REST web service.

Whenever we consume a WCF service from a client, we need to create a proxy and need to import all the types(xsd) to your client. Well, nothing wrong with this but think about a scenario if we can use all the web methods as they were a resource on a remote machine. REST will enable us to consume our web methods with good old Http verbs (GET,POST,PUT,DELETE).
Enough discussion right? Lets start some code ūüôā

Create WCF service
Data Contract

 <code> [DataContract]
 public partial class Employee
 public string Name { get; set; }</code>

 public string EmployeeID { get; set; }

 public string Email { get; set; }

Service contract Interface

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

using System.ServiceModel.Activation;
 public interface IEmployeeService
 [WebGet(UriTemplate = "/GetEmployees", ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json )]
 Employee[] GetEmployees();</code>

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

 [WebInvoke(UriTemplate = "/AddEmployee", Method = "POST",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
 Employee AddEmployee(Employee emp);

 [WebInvoke(UriTemplate = "/DeleteEmployee", Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
 bool DeleteEmployee(string EmployeeID);

1. UriTemplate is the url format which a client will request. lets say our service is accessed at “http:localhost:3839/Service1.svc” then “http:localhost:3839/Service1.svc/GetEmployees” will call the GetEmployees method which returns Employee[].

2. ResponseFormat/RequestFormat is the data format which is used to send/receive the data to/from server. JSON and XML are two formats supported by WCF.

3. WebGet and WebInvoke WebGet is used for GET requests and WebInvoke can specify any http verb with Method=”GET|POST|DELETE|PUT”.

Service Implementation

 <code>[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
 public class EmployeeService : IEmployeeService
 private List employees = null;
 #region IEmployeeService Members
 public Employee[] GetEmployees()
 employees = new List();
 employees.Add(new Employee() { EmployeeID = "1", Email = "", Name = "Praveen" });
 employees.Add(new Employee() { EmployeeID = "2", Email = "", Name = "Prashant" });
 employees.Add(new Employee() { EmployeeID = "3", Email = "", Name = "Ritu" });
 return employees.ToArray();

public Employee GetEmployeeDetails(string EmployeeID)
 return new Employee() { EmployeeID = EmployeeID, Email = "", Name = "sfsdgg" };

public Employee AddEmployee(Employee emp)
 return emp;

public bool DeleteEmployee(string EmployeeID)
 // delete in DB
 return true;

Note: You can replace these methods with something significant code ūüôā here it is just sample.

Web.config settings

 <services >
 <service name="WCFSamples.EmployeeService" behaviorConfiguration="restBehavior" >
 <endpoint address=""
 behaviorConfiguration="rest" >
 <identity >
 <dns value="localhost" />


 <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
 <behavior name="rest">
 <webHttp />
 <behavior name="restBehavior">
 <serviceMetadata httpGetEnabled="true" />
 <serviceDebug includeExceptionDetailInFaults="false" />
 <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

Note: For REST service Binding is always webHttpBinding also endpointbehavior also must be added like below.

<behavior name="rest">
<webHttp />

.Svc file markup 


<%@ ServiceHost Language="C#" Debug="true" Service="WCFSamples.EmployeeService" CodeBehind="Service1.svc.cs" %>

This is all we need to know about creating a WCF REST enabled service.
Next post will describe how to consume it in different ways.

Hope it helps!!