Web API Client Implementations - ASP.NET Web API 2: Beginner Guide (2015)

ASP.NET Web API 2: Beginner Guide (2015)

Web API Client Implementations

Web API can be consumed from different applications including web applications, client side technologies like jQuery and AngularJS, native mobile applications and so on. This section discuss about how we can invoke Web API from various client applications; ASP.NET MVC and jQuery.

Working with the HttpClient API

HttpClient is an extensible API for accessing any services or web sites exposed over HTTP. The HttpClient API was introduced as part of the WCF Web API but is now available as part of ASP.NET Web API in.NET Framework 4.5. You can use HttpClient to access Web API methods from a code-behind file and from services such as WCF.

The code snippet shown in Listing 4 creates an HttpClient object and uses it for asynchronous access to products API methods. Refer the code comments to understand the code snippet.

Listing 4: Creating an HttpClient object to access sample API methods

// asynchronous accessing of web api method

async Task GetData()


StringBuilder result = new StringBuilder();

// Define the httpClient object

using (HttpClient client = new HttpClient())


// Define the base address of the MVC application hosting the web api

// accessing the web api from the same solution

client.BaseAddress = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);

// Define the serialization used json/xml/ etc


new MediaTypeWithQualityHeaderValue("application/json"));

// Call the method

HttpResponseMessage response = client.GetAsync("api/products").Result;

if (response.IsSuccessStatusCode)


// Convert the result into business object

var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;

foreach (var p in products)


result.Append(string.Format("{0} --- [Price: {1} Category: {2}] ", p.Name, p.Price, p.Category));





result.Append(string.Format("Error Code:-{0} Error Details: {1}", (int)response.StatusCode, response.ReasonPhrase));



data.Text = result.ToString();


Accessing the Web API from jQuery

From an HTML5 Web application, you can use jQuery to directly access the Web API. You call the API by using the getJSON() method to extract the business object from the result. jQuery can identify internal fields associated with the business object, such as data[i].Price.

The code snippet in Listing 5 retrieves data from our Product API methods and displays the data in a tabular format. Refer the code comments to understand the code snippet.

Listing 5: Using jQuery to retrieve data from the Web API methods



<script src="Scripts/jquery-1.8.2.js"></script>

<script type="text/javascript">


function (data) {

//Clear the div displaying the result


//Create a table and append the table body

var $table = $('<table border="2">');

var $tbody = $table.append('<tbody />').children('tbody');

//data - return value from the Web API method

for (var i = 0; i < data.length; i++) {

//add a new row to the table

var $trow=$tbody.append('<tr />').children('tr:last');

//add a new column to display Name

var $tcol = $trow.append("<td/>").children('td:last')


//add a new column to display Category

var $tcol = $trow.append("<td/>").children('td:last')


//add a new column to display Price

var $tcol = $trow.append("<td/>").children('td:last')



//display the table in the div






<div id="productView"></div>



Passing a Parameter from jQuery

In addition to retrieving data from the Web API methods, you can use jQuery to pass parameters back to the Web API. jQuery supports several methods for passing the parameters. The first approach is to use separate parameter set. The following code snippet demonstrates how to pass a single parameter:


{ selectedId: '4' },

function (data) { ….});

You can also pass multiple parameters within a parameter set, as shown in the following snippet:


{ selectedId: '4', name: 'TV' },

function (data) { ….});

Another approach you can take is to pass a parameter by appending it to the URL query string, as shown in the following snippet:

$.getJSON("api/products?selectedId =4",

function (data) { ….});

First approach separates the query string or parameter passing from the URL and is appropriate for complex or multiple data passing. Second approach is more suitable for passing one or two parameters.