Thursday, March 6, 2014

How to invoke a Web API method within a controller.....


ASP.Net Web API is a powerful tool to retrieve data and to serve a broad range of clients. Once created, it can used to access data in mobile applications too.

   Web API's are helpful to create RESTful services and are similar to MVC controllers, but here the class will be derived from APIController when compared to MVC applications where it will be just Controller. This framework is really helpful to build HTTP based services and can very well control the returned data type  to be json or xml.

   If you are developing an application in MVC, it well suites to have Web API, as it is also based on routing concepts.

 Now lets get into the tutorial to see how to invoke a method in Web API....

 In your MVC controller method, make sure you invoke HttpClient to get started. (for HttpClient, if you have any issues, make sure you refer the namesapce : System.Net.Http;)

 We will use HttpClient and define the URI property within client object as below.....  This defines our base url that the web service is located at...

string url = "http://localhost:1001";
 using (HttpClient client = new HttpClient())
{
     client.BaseAddress = new Uri(url);
     client.DefaultRequestHeaders.Accept.Add(new                  
                                             MediaTypeWithQualityHeaderValue("application/json"));
      
}

In the above, we are using Headers property to define, what kind of data will be handled from server. In the above scenario, we are letting it know that we are dealing json format data. (you can even prefer to use xml format, based on what fits your need well).

Before invoking the method, we should make sure the controller name and method name that we are about to call for data. This defines our path, that we will be using with our client object.

Example : below is our Web API definition...


Given the class name is WebApiTestController, this is how we will use it with our client object.

HttpResponseMessage msg = client.GetAsync("api/WebApiTest/<MethodName>").Result;

Using the above, we can identify if our call was successful by trying the method :
 if(msg.IsSuccessStatusCode), then we had successfully accessed our method  and we can retrieve our data as below...

var mylist = msg.Content.ReadAsAsync<object>().Result;

To have the list converted to a compatible IList<T> object, you can use Result.ToList(); The resultset would be a List object.

  Below is the compiled list for complete code to invoke a web API method....




Happy coding...



No comments:

Post a Comment