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.

Prerequisites:

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

We will use the dummy API for this purpose.

https://api.myjson.com/bins/zg8of

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("https://api.myjson.com/bins/zg8of");
            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();
            }
            httpResponse.Close();
            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">
    <tr>
        <th>Name</th>
        <th>Month</th>
        <th>Sales_Figure</th>
        <th>Perc</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Month</td>
            <td>@item.Sales_Figure</td>
            <td>@item.Perc</td>
        </tr>
    }
</table>

Output;

output