.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh
Melody Anderson
Eminent IT

Home >> Articles >> Silverlight >> Post New Resource Bookmark and Share   

 Subscribe to Articles

WebClient and HttpWebRequest class : Tutorial

Posted By:Dhananjay Kumar       Posted Date: January 02, 2010    Points: 25    Category: Silverlight    URL: http://www.dotnetspark.com  

WebClient and HttpWebRequest class : Tutorial


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.


  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 Silverlight?
  1. HTTP based service returned data on a HTTP request in a particular URI
  2. HTTP request can be send any type of URI like,



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

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

Silverlight 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.

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 web page.

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";

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

    WebClient wc = new WebClient();
  4. 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.
  5. Now need to call , 

    Uri uri = new Uri(baseuri);
  6. 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 products = query.ToList() as List;
  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 JsonArray;     var query = from product in json
  select new Product
     ProductId = (int)product["ProductId"],
     ProductName = (string)product["ProductName"],
     UnitPrice = (decimal)product["UnitPrice"]
  List products = query.ToList() as List;
  lstProducts.DataContext = products;

For Desterilizing as JOSN using DataContractJsonSerliazer


  1. 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.
  2. 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!

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend