On my last tutorial I taught How to Implement ASP NET Web API which returned products from database in JSON. Now I will consume this Web API in ASP.NET MVC.
Let start with the API consuming part.
Do you remember the GetProduct() method of the API that returns products, based on page-by-page manner, in JSON? I will call this method from my MVC website and display the JSON data in HTML table format. While calling this method I also require to provide the API Key and Secret on the request header.
Create a Model class and name it APICall.cs. Add this code in it:
public class APICallProduct
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int SupplierID { get; set; }
public int CategoryID { get; set; }
public string QuantityPerUnit { get; set; }
public double UnitPrice { get; set; }
public int UnitsInStock { get; set; }
public int UnitsOnOrder { get; set; }
public int ReorderLevel { get; set; }
public bool Discontinued { get; set; }
}
public class ResponseAPICallProduct
{
public int Total { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
public List<APICallProduct> Product { get; set; }
}
Note: The ResponseAPICallProduct class will capture the JSON response.
Create a Controller and add the following code to it:
public ActionResult Index(string key, string secret, int? page)
{
if (page != null)
GetProduct(key, secret, Convert.ToInt32(page));
return View();
}
[HttpPost]
[ActionName("Index")]
public ActionResult Index_Post(string key, string secret, int? page)
{
if (string.IsNullOrEmpty(key))
ModelState.AddModelError("key", "Please enter API Key");
if (string.IsNullOrEmpty(secret))
ModelState.AddModelError("secret", "Please enter API Secret");
if (ModelState.IsValid)
GetProduct(key, secret, Convert.ToInt32(page));
return View();
}
public void GetProduct(string key, string secret, int page)
{
int pageNo = page == 0 ? 1 : Convert.ToInt32(page);
HttpWebRequest apiRequest = WebRequest.Create("http://localhost:64253/api/API/" + pageNo + "") as HttpWebRequest;
apiRequest.Headers.Add("Key", key);
apiRequest.Headers.Add("Secret", secret);
StringBuilder sb = new StringBuilder();
string apiResponse = "";
try
{
using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
apiResponse = reader.ReadToEnd();
ResponseAPICallProduct rootObject = JsonConvert.DeserializeObject<ResponseAPICallProduct>(apiResponse);
sb.Append("<div class=\"resultDiv\"><table><tr><td>Product Id</td><td>Product Name</td><td>Supplier Id</td><td>Category Id</td><td>Quantity Per Unit</td><td>Unit Price</td><td>Units In Stock</td><td>Units On Order</td><td>Reorder Level</td><td>Discontinued</td></tr>");
foreach (APICallProduct product in rootObject.Product)
{
sb.Append("<tr><td>" + product.ProductID + "</td><td>" + product.ProductName + "</td><td>" + product.SupplierID + "</td><td>" + product.CategoryID + "</td><td>" + product.QuantityPerUnit + "</td><td>" + product.UnitPrice + "</td><td>" + product.UnitsInStock + "</td><td>" + product.UnitsOnOrder + "</td><td>" + product.ReorderLevel + "</td><td>" + product.Discontinued + "</td></tr>");
}
sb.Append("</table></div>");
int pageSize = 10;
PagingInfo pagingInfo = new PagingInfo();
pagingInfo.CurrentPage = pageNo;
pagingInfo.TotalItems = rootObject.Total;
pagingInfo.ItemsPerPage = pageSize;
ViewBag.Paging = pagingInfo;
}
}
catch (System.Net.WebException ex)
{
sb.Append(ex.Message);
}
ViewBag.Result = sb.ToString();
}
When the API sends the response in JSON I am doing these things:
Since I get the JSON in page-by-page manner therefore I am also creating the paging links. For this I am using a custom built PagingInfo class which you can find it inside the code that you download from here (download link provided at the end).
This PagingInfo class values are filled and also send to the View using another ViewBag object.
Create the View and add the following code:
@using demo.MVC.Class; @*PagingInfo namespace*@
@model demo.MVC.Models.ResponseAPICallProduct
<div id="apiDiv">
<h4>Enter your API Key & Secret</h4>
<p>Use (Key = Key1, Secret = Secret1) or (Key = Key2, Secret = Secret2) or (Key = Key3, Secret = Secret3)</p>
@using (Html.BeginForm())
{
@Html.TextBox("key", "Key1")
@Html.ValidationMessage("key")
@Html.TextBox("secret", "Secret1")
@Html.ValidationMessage("secret")
<button id="submit">Submit</button>
}
<div id="message">
@(new HtmlString(ViewBag.Result))
</div>
<div class="pagingDiv">
@{
PagingInfo pagingInfo = (PagingInfo)ViewBag.Paging;
if (pagingInfo != null)
{
@Html.PageLinks(pagingInfo, x => Url.Action("Index", "APICall", new { page = x, key = Request.QueryString["key"], secret = Request.QueryString["secret"] }))
}
}
</div>
</div>
@Scripts.Render("~/jQuery")
<script>
$(document).ready(function () {
$("#submit").click(function (e) {
$("form").attr("action", "/ApiCall" + "?key=" + $("#key").val() + "&secret=" + $("#secret").val());
});
});
</script>
Explanation
Run the application and navigate to the URL – http://localhost:64253/ApiCall. Add the API Key & Secret to the 2 text boxes and press the button. You will see the products displayed in table format like that shown below:
If you enter wrong Key or Secret then you will receive (403) Forbidden response from the API.
Next I am consuming the SearchProduct() method of the API that allows to search the Products by name. To call this API method, I have to add 2 new Actions on the controller (Search & Search_Post).
public ActionResult Search(string name)
{
return View();
}
[HttpPost]
[ActionName("Search")]
public ActionResult Search_Post(string name)
{
if (string.IsNullOrEmpty(name))
{
ModelState.AddModelError("name", "Please enter your name");
}
if (ModelState.IsValid)
{
string key = "Key1", secret = "Secret1";
HttpWebRequest apiRequest = WebRequest.Create("http://localhost:64253/api/API/" + name + "") as HttpWebRequest;
apiRequest.Method = "Post";
apiRequest.ContentType = "application/x-www-form-urlencoded";
apiRequest.ContentLength = 0;
apiRequest.Headers.Add("Key", key);
apiRequest.Headers.Add("Secret", secret);
StringBuilder sb = new StringBuilder();
string apiResponse = "";
try
{
using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
apiResponse = reader.ReadToEnd();
ResponseAPICallProduct rootObject = JsonConvert.DeserializeObject<ResponseAPICallProduct>(apiResponse);
sb.Append("<div class=\"resultDiv\"><table><tr><td>Product Id</td><td>Product Name</td><td>Supplier Id</td><td>Category Id</td><td>Quantity Per Unit</td><td>Unit Price</td><td>Units In Stock</td><td>Units On Order</td><td>Reorder Level</td><td>Discontinued</td></tr>");
foreach (APICallProduct product in rootObject.Product)
sb.Append("<tr><td>" + product.ProductID + "</td><td>" + product.ProductName + "</td><td>" + product.SupplierID + "</td><td>" + product.CategoryID + "</td><td>" + product.QuantityPerUnit + "</td><td>" + product.UnitPrice + "</td><td>" + product.UnitsInStock + "</td><td>" + product.UnitsOnOrder + "</td><td>" + product.ReorderLevel + "</td><td>" + product.Discontinued + "</td></tr>");
sb.Append("</table></div>");
}
}
catch (System.Net.WebException ex)
{
sb.Append(ex.Message);
}
ViewBag.Result = sb.ToString();
}
return View();
}
Note: Since this is a POST Method so I have added the code line apiRequest.Method = “Post”;.
The JSON response which I get from the API is converted to HTML table and then added to a ViewBag object. This ViewBag object’s value is shown on the View.
Add Search.cshtml View and add to it the code shown below:
<div id="apiDiv">
<h4>Enter the Search Text and Press Submit Button</h4>
@using (Html.BeginForm())
{
@Html.TextBox("name")
<button id="submit">Submit</button>
@Html.ValidationMessage("name")
}
<div id="message">
@(new HtmlString(ViewBag.Result))
</div>
</div>
Here, on the button click event of the view, the ASP.NET Web API consuming procedure starts.
Now run this URL (http://localhost:64253/ApiCall/Search) on your browser. Add Chai to the text box and press the button.
You will get back the ‘Chai’ Product information from the API.
Download link:
Conclusion
I hope you enjoyed this tutorial. The below 2 links are it’s other parts.
Save these 3 links for your future reference.