Skip to main content

Example of calling a RESTful web service API within an ASP.NET MVC Controller, and returning a JSON result.

using System.Net.Http;
using System.Web.Mvc;
using AsyncWebApps.Web.ViewModels;
using System.Threading;
using System.Threading.Tasks;
using System;
using System.Net.Http.Headers;

namespace AsyncWebApps.Web.Controllers
{
    [RoutePrefix("vehicles")]
    public class HomeController : Controller
    {
        [Route("~/", Name = "Home")]
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [Route("cars")]
        public async Task<ActionResult> Cars()
        {
            var task = GetHttpStringAsync("https://example.com/api/search?cars=all");
            var result = await task;

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [NonAction]
        private static async Task<String> GetHttpStringAsync(string url)
        {
            var responseContent = string.Empty;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders
                      .TryAddWithoutValidation("Accept", "application/json");

                using (var response = await client.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        using (var content = response.Content)
                        {
                            responseContent = await content.ReadAsStringAsync();
                        }
                    }
                    else
                    {
                        throw new Exception(
                            string.Format("{0}-{1}",
                                (int)response.StatusCode, response.StatusCode));
                    }
                }
            }

            return responseContent;
        }
    }
}