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.

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

2 Comments

  1. Arne Sauer

    Hi,
    thank you for the good an short tutorial, but the https://api.myjson.com/bins/zg8of is not available. I used https://api.predic8.de/shop/products/ instead for the example. But for this you have to change the model as shown in the last answer to the following question:
    https://stackoverflow.com/questions/42914812/net-deserialize-json-from-get-api-with-header-from-c-sharp

    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; }
    }

    0
    0
    Reply
  2. Deepansh Yadav

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

    0
    0
    Reply

Submit a Comment

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

Subscribe

Select Categories