WebGet and HttpWebRequest class


 This article will discuss about, different way of consuming HTTP enabled service (like REST).This article, will explain about WebGet and HttpWebRequest. Before reading this article, I will suggest readers to read my previous articles on REST, ADO.NET Data Service and Cross Domain issue on our site.Assumption

  1. Already REST service has been created and hosted within placed client access policy file.
  2. There is a SilverLight Client. Which is going to consume WebGet service of REST

How to access HTTP based service in Silver Light?

  1. HTTP based service returned data on a HTTP request in a particular URL
  2. HTTP request can be send any type of URI like




  3. HTTP request is cofigured to work with , verb GET
  4. Required parameter to invoke service (WebGet sercvice) should be appended with URI 


  1. The output service data is contained in HTTP Response.
  2. Format of data depends on service implementation, but it mainly in format of JOSN, XML or RSS.

    Silver Light provides two methods for sending HTTP request

    1. WebClient
    2. HttpWebRequest

Difference between WebClient and HttpWebRequest

  1. HttpWebRequest supports large subset of HTTP Protocol , which makes it better option for advanced scenarios
  2. HttpWebRequest uses asynchronous programming model which uses delegates but on the other hand WebClient uses event based asynchronous programming model. So it is easier to use and it needs lessee line of code.
  3. Callback for WebClient is raised for HTTP Response and it is invoked on the same user interface thread. So it is easier to update property of UI element. That is why it is easy with WebClient to bind UI properties with data of Http response
  4. Whereas, HttpWebRequest callback run on different thread. So there is need of write extra code for UI binding.  


Namespace:  System.Net

WebClient class is being used in SilverLight control which is hosted in a webpage.

The following table describes WebClient methods for uploading data to a resource.

Method Description
OpenWriteAsync Retrieves a Stream used to send data to the resource asynchronously, without blocking the calling thread.
UploadStringAsync Sends a String to the resource, without blocking the calling thread.

 The following table describes WebClient methods for downloading data from a resource.

Method Description
DownloadStringAsync Downloads a String from a resource, without blocking the calling thread.
OpenReadAsync Returns the data from a resource asynchronously, without blocking the calling thread.


Steps to call Http based service


  1. Create URI , where request is to be sent  

    string baseuri = http://trvlsdw002/synergyservices/appointmentservice.svc/Appointments;

  1. Take care of cross domain issue here.
  2. Create instance of WebClient. don’t forget to ass namespace System.Net

    WebClient wc = new WebClient();     

  3. Now ,
    wc.DownloadStringCompleted += ParseProducts_AsXml;

Here ParseProducts_AsXml is event , which will parse HTTP Response in XML format

If response format is JSON , then
wc.DownloadStringCompleted += ParseProducts_AsJson

Note : Here , ParseProducts_AsXml and ParseProducts_AsJson are user defined events. We need to define these events later.

  1. Now need to call , 
    uri = new Uri(baseuri);


  1. Parse the response either as XML or as JOSN depending on response type of Http Response.

    For parsing as XML, given code might help. Here response is being passed in Product business object. In e.Result, result stream is coming to SilverLight application. Just need to desterilize that.

private void ParseProducts_AsXml(object sender, DownloadStringCompletedEventArgs e)


string abc = “”;
string rawXmlresponse = e.Result;

XDocument xdoc = XDocument.Parse(rawXmlresponse);

var query = from product in xdoc.Descendants(abc + “Product”)

select new Product

ProductId = product.Element(“ProductId”).Value.ToInt(),

 ProductName = product.Element(“ProductName”).Value,
UnitPrice = product.Element(“UnitPrice”).Value.ToDecimal()


List<Product> products = query.ToList() as List<Product>;

lstProducts.DataContext = products;


For parsing as JOSN below code might help.
private void ParseProducts_AsJson(object sender, DownloadStringCompletedEventArgs e)


string raw = e.Result;

JsonArray json;

if (JsonArray.Parse(raw) as
JsonArray == null)

json = new
JsonArray { JsonObject.Parse(raw) as
JsonObject };


json = JsonArray.Parse(raw) as

var query = from product in jso



ProductId = (int)product[“ProductId”],

ProductName = (string)product[“ProductName”],

UnitPrice = (decimal)product[“UnitPrice”]


List<Product> products = query.ToList() as

lstProducts.DataContext = products;


For Desterilizing as JOSN using DataContractJsonSerliazer

void ParseProducts_AsJson_UsingDataContractJsonSerializer(

object sender, DownloadStringCompletedEventArgs e)

string json = e.Result;

DataContractJsonSerializer serializer =

//DataContractJsonSerializer serializer = new DataContractJsonSerializer(products.GetType());

MemoryStream stream =newMemoryStream(Encoding.UTF8.GetBytes(json));

 List<Product> products = serializer.ReadObject(stream) as


lstProducts.DataContext = products;




 There is no direct way, to expose DataContract to client in RESTful service. So workaround need to be done. There is need to create Business class at SilverLight client side. In above examples business class is Product.

  1. All the code written above is consuming REST service, which is returning List of appointments.



[WebGet(UriTemplate = “/Appointments/”)]

List<AppointmentDTO> GetAppointments();

Here, AppointmentDTO is business object. Which has to be created at client side too?

Happy Coding

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Create a website or blog at WordPress.com