Sunday, May 27, 2012

MVC Webapi

Today, I'm posting about WebApi. Recently, I've looked some example of Webapi on other blogs. Recently, found some of other people's conversation from other sites.

1.Introduction to HttpClient HttpClient provides a flexible and extensible API for accessing all things exposed through HTTP. We used to use it for a while as part of WCF Web API. It is now part of ASP.NET Web API and in .NET 4.5 which is make developer to easier to develop.
System.Net.Http: it provides the basic HttpClient and related classes System.Net.Http.Formatting: Adds support for serialization, deserialization as well as for many additional features building on top of System.Net.Http System.Json: it is for JsonVaue which is a mechanism for reading and manipulating JSON documents
Please see below the sample code which I found it on msdn blog (

   1:  static void Main(string[] args) 
   2:          { 
   3:              // Create an HttpClient instance 
   4:              HttpClient client = new HttpClient(); 
   6:              // Send a request asynchronously continue when complete 
   7:              client.GetAsync(_address).ContinueWith( 
   8:                  (requestTask) => 
   9:                  { 
  10:                      // Get HTTP response from completed task. 
  11:                      HttpResponseMessage response = requestTask.Result; 
  13:                      // Check that response was successful or throw exception 
  14:                      response.EnsureSuccessStatusCode(); 
  16:                      // Read response asynchronously as JsonValue and write out top facts for each country 
  17:                      response.Content.ReadAsAsync<JsonArray>().ContinueWith( 
  18:                          (readTask) => 
  19:                          { 
  20:                              Console.WriteLine("First 50 countries listed by The World Bank..."); 
  21:                              foreach (var country in readTask.Result[1]) 
  22:                              { 
  23:                                  Console.WriteLine("   {0}, Country Code: {1}, Capital: {2}, Latitude: {3}, Longitude: {4}", 
  24:                                      country.Value["name"], 
  25:                                      country.Value["iso2Code"], 
  26:                                      country.Value["capitalCity"], 
  27:                                      country.Value["latitude"], 
  28:                                      country.Value["longitude"]); 
  29:                              } 
  30:                          }); 
  31:                  }); 
  33:              Console.WriteLine("Hit ENTER to exit..."); 
  34:              Console.ReadLine(); 
  35:          }

Just a little defination for HttpClient: Itis the main class for sending and receiving HttpRequestMessages and HttpResponseMessages. If you are used to using WebClient or HttpWebRequest.

An HttpClient instance is the place to configure extensions, set default headers, cancel outstanding requests and more.

  1. You can issue as many requests as you like through a single HttpClient instance.
  2. HttpClients are not tied to particular HTTP server or host; you can submit any HTTP request using the same HttpClient instance.
  3. You can derive from HttpClient to create specialized clients for particular sites or patterns
  4. HttpClient uses the new Task-oriented pattern for handling asynchronous requests making it dramatically easier to manage and coordinate multiple outstanding requests.

As you know HttpResponseMessage contains information about the response including the status code, headers, and any content body.

The content body is encapsulated in HttpContent which captures content headers such as Content-Type, Content-Encoding. we can read the content as JsonArray as well as any number of ReadAs* methods.

please see the more deail here
public class Contact
    public int Id { get; set; }
    public string Name { get; set; }
   1:  var url = "http://localhost:9000/api/contacts";
   2:  using (var client = new WebClient())
   3:  using (var reader = XmlReader.Create(client.OpenRead(url)))
   4:  {
   5:      var serializer = new XmlSerializer(typeof(Contact[]));
   6:      var contacts = (Contact[])serializer.Deserialize(reader);
   7:      // TODO: Do something with the contacts
   8:  }

No comments: