ASP.NET MVC 4 Application Calling Remote WebAPI

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

Leave a Comment