ASP.NEt MVC using Web API to return a Razor view

You could send an HTTP request to your Web API controller from within the ASP.NET MVC controller:

public class ProductController : Controller
{
    public ActionResult Index()
    {
        var client = new HttpClient();
        var response = client.GetAsync("http://yourapi.com/api/products").Result;
        var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
        return View(products);
    }
}

Also if you can take advantage of the .NET 4.5 async/await it is strongly recommended to do so to avoid blocking calls:

public class ProductController : Controller
{
    public async Task<ActionResult> Index()
    {
        var client = new HttpClient();
        var response = await client.GetAsync("http://yourapi.com/api/products");
        var products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
        return View(products);
    }
}

Leave a Comment