Consuming Web Services In ASP.NET MVC 5 Application

Let us say there exist a RESTful Web Service, e.g. Web API service, and you want to create a new MVC application that consume this Web Service. I designed a simple way to achieve the goal.

From Visual Studio wizard create a new MVC 5 Project.

By default you‘ll find 3 standard controllers: Account, Manage and Home.

And all inherits from Controller.

Now create a new MVC 5 controller and name it: “BaseController”.

Change the generalization of the other controllers and implement the BaseController. I have shown it in the following screenshot under Home Controller,

Suppose now there exist a web API service,

And you want contact this for get your Business Object Info as :

  • Products Detail: localhost:50665\api\Products
  • Orders Detail: localhost:50665\api\Orders
  • Customers Detail: localhost:50665\api\Customers
  • Invoice Detail: localhost:50665\api\Document\GetInvoice?num=1

So, I think I found a very easy way,

I created Base Controller, a generic method (GetWSObject) for contacting the WebService from all Controller and returned my desired object as a dynamic object:

  1. public async Task < T > GetWSObject < T > (string uriActionString)  
  2. {  
  3.     T returnValue =  
  4.         default (T);  
  5.     try  
  6.     {  
  7.         using(var client = new HttpClient())  
  8.         {  
  9.             client.BaseAddress = new Uri(@ "http://localhost:50665/");  
  10.             client.DefaultRequestHeaders.Accept.Clear();  
  11.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  12.             HttpResponseMessage response = await client.GetAsync(uriActionString);  
  13.             response.EnsureSuccessStatusCode();  
  14.             returnValue = JsonConvert.DeserializeObject < T > (((HttpResponseMessage) response).Content.ReadAsStringAsync().Result);  
  15.         }  
  16.         return returnValue;  
  17.     }  
  18.     catch (Exception e)  
  19.     {  
  20.         throw (e);  
  21.     }  
  22. }  

The method takes the uriActionString as an input parameter and returns the result dynamically deserialized as my business model object .

So, for example, if you want to take the detail for Product with id=11 and show this in your MVC application in the HomeControllers (that implement the BaseController) you can create the following ActionResult:

  1. public async Task < ActionResult > ViewProduct(int Id)  
  2. {  
  3.     ViewBag.Message = "Your products page.";  
  4.     Product product = new Product();  
  5.     string urlAction = String.Format("/api/Products/{0}", Id);  
  6.     product = await GetWSObject < Product > (urlAction);  
  7.     return View(product);  
  8. }  

With 2 lines you get the result and you have a Product object to pass (e.g.) in your View as a viewmodel.

Obviously, with the same modalities you can contact any other method of the Web Service, from any other Controller; simply change the urlAction string and call the GetWSObject method passing the desired result object type (<Product>). That's all!


Similar Articles