Tutorial – Consuming ASP NET Web API from Start [with Code]

Tutorial – Consuming ASP NET Web API from Start [with Code]

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.

Consuming ASP NET Web API – GetProduct() method

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.

Model Code

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.

Controller Code

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();
}
Explanation
  • I will be sending the API Key, Secret and Page number in the query string, so am having these 3 parameters on my Index GET and POST actions.
  • The function GetProduct() which is called both from Index GET and POST actions, does the consuming of this Web API. It makes the API request to the URL (http://localhost:64253/api/API/) and passes the current page number to it. So that means the GetProduct() method of my ASP.NET MVC Web API is called.
  • The API Key and Secret are added to the request header.

When the API sends the response in JSON I am doing these things:

  • Serializing it into the ResponseAPICallProduct class with the help of JsonConvert (namespace Newtonsoft.Json;).
  • I then loop through all the products of ResponseAPICallProduct class and create HTML table with the help of a StringBuilder.
  • This HTML table is send to the view using a ViewBag object at the very end of the code.

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.

To understand how paging links are created, please read How to Create ASP.NET MVC Paging article.
View Code

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

  • The View has 2 text boxes where user has to enter the Key and Secret.
  • The Products, which are in HTML Table format, are shown inside the div called ‘message’ from the ViewBag.Result object. The paging links are shown inside the pagingDiv from the ViewBag.Paging object.
  • A small jQuery code at the bottom of the view is meant to add the API Key and Secret to the URL.

Testing the Web API

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:

api result

If you enter wrong Key or Secret then you will receive (403) Forbidden response from the API.

403 forbidden response

Consuming ASP NET Web API – SearchProduct() method

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.

View Code

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.

Testing the Web API

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.

chai product search through API

Download link:

DOWNLOAD

Conclusion
I hope you enjoyed this tutorial. The below 2 links are it’s other parts.

Save these 3 links for your future reference.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate