Consuming Rest API From Controller In ASP.NET MVC

Here, we will learn about consuming Rest API from the controller in ASP.NET MVC. We can also use ajax for this, but this will require jQuery for it. So we can also consume the rest API directly from the controller and process its result.


  • Basic knowledge of ASP.NET MVC
  • Basic knowledge of Rest API

We will use the dummy API for this purpose.

Create a new project in ASP.NET MVC 5 and goto HomeController

Add the following code in it.

public class HomeController : Controller
        public ActionResult Index()
            List<MapApi> result = null;
            string response = string.Empty;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("");
            httpWebRequest.ContentType = "application/json; charset=utf-8";
            httpWebRequest.Method = "GET";
            httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
                response = streamReader.ReadToEnd();
            result = Deserialize<List<MapApi>>(response);
            return View(result);
        public static T Deserialize<T>(string jsonData)
            JsonSerializer json = new JsonSerializer();
            return json.Deserialize<T>(new JsonTextReader(new StringReader(jsonData)));

Create a new class as MapApi.cs in Model folder.

public class MapApi
        public string Name { get; set; }
        public string Month { get; set; }
        public string Sales_Figure { get; set; }
        public string Perc { get; set; }

Finally, go to Index.cshtml and add the code in it.

    ViewBag.Title = "Home Page";

<table class="table table-bordered table-hover">
    @foreach (var item in Model)




  1. Arne Sauer

    thank you for the good an short tutorial, but the is not available. I used instead for the example. But for this you have to change the model as shown in the last answer to the following question:

    I changed the code in the controller to:

    var track = JsonConvert.DeserializeObject(response);

    //result = Deserialize<List>(response);
    return View(track.Products);

    for the ProductModel:
    public class ProductModel
    [JsonProperty(PropertyName = “meta”)]
    public Meta Metas { get; set; }

    [JsonProperty(PropertyName = “products”)]
    public IEnumerable Products { get; set; }

  2. Deepansh Yadav

    If we use null for the variable then it will create the nullrefrence exception.


Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories