Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 Application Calling Remote WebAPI

I've created a couple ASP.NET MVC applications in the past, but I've never used WebAPIs before. I'm wondering how I could create a simple MVC 4 app that does simple CRUD stuff via WebAPI instead of through a normal MVC controller. The trick is that the WebAPI should be a separate solution (and, in fact, could very well be on a different server/domain).

How do I do that? What am I missing? Is it just a matter of setting up routes to point to the WebAPI's server? All the examples I've found showing how to consume WebAPIs using an MVC application seem to assume the WebAPI is "baked in" to the MVC application, or at least is on the same server.

Oh, and to clarify, I'm not talking about Ajax calls using jQuery... I mean that the MVC application's controller should use the WebAPI to get/put data.

like image 577
Glenn Arndt Avatar asked Nov 02 '12 17:11

Glenn Arndt


People also ask

Can we call Web API from MVC controller?

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.

Can we use Web API in MVC?

First of all, create MVC controller class called StudentController in the Controllers folder as shown below. Right click on the Controllers folder > Add.. > select Controller.. Step 2: We need to access Web API in the Index() action method using HttpClient as shown below.


1 Answers

You should use new HttpClient to consume your HTTP APIs. What I can additionally advise you to make your calls fully asynchronous. As ASP.NET MVC controller actions support Task-based Asynchronous Programming model, it is pretty powerful and easy.

Here is an overly simplified example. The following code is the helper class for a sample request:

public class CarRESTService {      readonly string uri = "http://localhost:2236/api/cars";      public async Task<List<Car>> GetCarsAsync() {          using (HttpClient httpClient = new HttpClient()) {              return JsonConvert.DeserializeObject<List<Car>>(                 await httpClient.GetStringAsync(uri)                 );         }     } } 

Then, I can consume that through my MVC controller asynchronously as below:

public class HomeController : Controller {      private CarRESTService service = new CarRESTService();      public async Task<ActionResult> Index() {          return View("index",             await service.GetCarsAsync()         );     } } 

You can have a look at the below post to see the effects of asynchronous I/O operations with ASP.NET MVC:

My Take on Task-based Asynchronous Programming in C# 5.0 and ASP.NET MVC Web Applications

like image 55
tugberk Avatar answered Oct 17 '22 06:10

tugberk