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:
- public async Task < T > GetWSObject < T > (string uriActionString)
- {
- T returnValue =
- default (T);
- try
- {
- using(var client = new HttpClient())
- {
- client.BaseAddress = new Uri(@ "http://localhost:50665/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = await client.GetAsync(uriActionString);
- response.EnsureSuccessStatusCode();
- returnValue = JsonConvert.DeserializeObject < T > (((HttpResponseMessage) response).Content.ReadAsStringAsync().Result);
- }
- return returnValue;
- }
- catch (Exception e)
- {
- throw (e);
- }
- }
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:
- public async Task < ActionResult > ViewProduct(int Id)
- {
- ViewBag.Message = "Your products page.";
- Product product = new Product();
- string urlAction = String.Format("/api/Products/{0}", Id);
- product = await GetWSObject < Product > (urlAction);
- return View(product);
- }
With 2 lines you get the result and you have a Product object to pass (e.g.) in your View as a viewmodel.