http://www.developer.com/net/asp/consuming-an-asp.net-web-api-using-httpclient.html

Back to article

Consuming an ASP.NET Web API Using HttpClient


May 17, 2012

Introduction

HttpClient is a modern HTTP client for .NET applications. It can be used to consume functionality exposed over HTTP. For example, a functionality exposed by an ASP.NET Web API can be consumed in a desktop application using HttpClient. Using HttpClient you can send requests and receive responses using standard HTTP verbs such as GET, POST, PUT and DELETE. In this article you will learn how to use HttpClient to consume ASP.NET Web API.

What is HttpClient?

HttpClient is a component that acts as an HTTP client for .NET applications. Consider a case where you have developed an ASP.NET Web API service to expose certain functionality. If you wish to consume this functionality in a web application, you will typically use a client side script (JavaScript, jQuery) to invoke GET, POST, PUT and DELETE operations. What if you wish to consume the same Web API in a desktop application or a console application? That is where HttpClient comes into picture.

As of this writing, HttpClient is in Beta stage and is available as a NuGet package. You must install the following NuGet packages before working with any of the examples discussed in this article:

  • System.Net.Http: Provides the basic HttpClient and related classes
  • System.Net.Http.Formatting: Support for serialization, deserialization and additional features
  • System.Json: Support for JsonValue, which is a mechanism for reading and manipulating JSON documents

HttpClientDemo - Manage NuGet Packages
HttpClientDemo - Manage NuGet Packages (Full size image)

As far as consuming ASP.NET Web API is concerned, the HttpClient class provides the following methods:

Method Description
GetAsync Sends a GET request to a specified URI
PostAsync Sends a POST request to a specified URI
PutAsync Sends a PUT request to a specified URI
DeleteAsync Sends a DELETE request to a specified URI

The ASP.NET Web API

Many modern internet based applications need to expose services over plain HTTP rather than making use of messaging formats such as SOAP. That is where ASP.NET Web API comes into the picture. Using ASP.NET Web API, you can program for HTTP verbs such as GET, POST, PUT and DELETE. Once created you can consume the Web API in a wide range of clients including web applications, desktop applications and mobile applications. This article will not discuss Web API in detail, it is assumed that you are familiar with ASP.NET Web API. You may consider reading Introduction to ASP.NET Web API before going any further. You will be using the same Customer Web API developed in the said article. It is recommended that you download the code associated with that article and have a look at the Customer Web API.

The Customer Web API consists of a Customer ApiController that has the following methods:

Method HTTP Verb Description
Get() GET Returns all the Customer records as an IEnumerable
Get(string) GET Returns a specific Customer object matching the specified CustomerID
Post(Customer) POST Inserts a new Customer into the database
Put(string, Customer) PUT Updates an existing Customer from the database based on a specific CustomerID
Delete(string) DELETE Deletes an existing Customer from the database based on a specific CustomerID

The actual database interaction happens via Entity Framework Data Model classes. The following figure shows the Customer data model class.

The Customer data model class
The Customer data model class

Creating a Helper for Calling Web API

Now that you have some idea about HttpClient, let's develop a console application that will call all the methods exposed by the Customer Web API. Begin by adding a new Console Application in the same solution as the Customer Web API.

The Console Application also needs the Customer data model class. So, add an Entity Framework Data Model to the Console Application project and create a data model for Customers table of Northwind database (see earlier figure). Then add a new class to the Console Application project and name it as WebAPIHelper. The following code shows the skeleton of the WebAPIHelper class.

public class WebAPIHelper
{
    public WebAPIHelper(string url)
    {
     ...
    }

    public Customer[] Get(string customerId = "")
    {
     ...
    }

    public string Post(Customer obj)
    {
     ...
    }

    public string Put(string customerId, Customer obj)
    {
     ...
    }

    public string Delete(string customerId)
    {
     ...
    }
}

As you can see, the WebAPIHelper class has four methods corresponding to each of the Web API methods, viz. Get(), Post(), Put() and Delete(). The constructor accepts a URL where the Web API can be found. Now, let's complete each of the methods shown above, one by one, and complete the WebAPIHelper class.

The Constructor

private string url = "";
HttpClient client = new HttpClient();

public WebAPIHelper(string url)
{
    this.url = url;
}

The constructor of WebAPIHelper class takes the URL of the Web API as the parameter and stores the supplied value in a local variable for later use. At the class level you also declare an instance of HttpClient class. The instance of HttpClient will be used inside all the other methods.

The Get() Method

public Customer[] Get(string customerId = "")
{
    if (customerId == "")
    {
        HttpResponseMessage response = client.GetAsync(this.url).Result;
        Customer[] data = JsonConvert.DeserializeObject<Customer[]>(response.Content.ReadAsStringAsync().Result);
        return data;
    }
    else
    {
        HttpResponseMessage response = client.GetAsync(this.url + customerId).Result;
        Customer obj = JsonConvert.DeserializeObject<Customer>(response.Content.ReadAsStringAsync().Result);
        Customer[] data = new Customer[1];
        data[0] = obj;
        return data;
    }
}

The Get() method accepts an optional parameter customerId. If this parameter is supplied, only a single Customer object will be retrieved, otherwise all Customer items will be retrieved. The return type of Get() method is an array of Customer objects.

Inside, you call the GetAsync() method on the HttpClient instance. The Result property will return an instance of HttpResponseMessage class. The HttpResponseMessage class represents an HTTP response. The Customer data can be accessed by reading the Content property of the HttpResponseMessage. The ReadAsStringAsync() method does just that. Notice the use of the JsonConvert class to deserialize the data as .NET objects. The JsonConvert class is provided by th4 Json.NET component that you need to refer in your project.

The Post() Method

public string Post(Customer obj)
{
    HttpRequestMessage request = new HttpRequestMessage();
    MediaTypeFormatter[] formatter = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };
    var content = request.CreateContent<Customer>(obj, MediaTypeHeaderValue.Parse("application/json"), formatter, new FormatterSelector());
    HttpResponseMessage response = client.PostAsync(this.url, content).Result;
    return response.Content.ToString();
}

The Post() method accepts a Customer object to be added to the database. The Customer object is then converted into an ObjectContent using the CreateContent() method. The CreateContent() method accepts the object, the content type, MediaTypeFormatter and a FormatterSelector. A MediaTypeFormatter handles the serialization and deserialization of the data during the request and a FormatterSelector selects a MediaTypeFormatter. As you might have guessed, the JsonMediaTypeFormatter class is intended to handle JSON data. The PostAsync() method makes a POST request to the Web API in an asynchronous fashion.

The Put() Method

public string Put(string customerId, Customer obj)
{
    HttpRequestMessage request = new HttpRequestMessage();
    MediaTypeFormatter[] formatter = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };
    var content = request.CreateContent<Customer>(obj, MediaTypeHeaderValue.Parse("application/json"), formatter, new FormatterSelector());
    HttpResponseMessage response = client.PutAsync(this.url + customerId, request.Content).Result;
    return response.Content.ToString();
}

The Put() method is similar to the Post() method discussed earlier. This time, however, you use the PutAsync() method to make a PUT request. Notice that a Put() Web API method takes two parameters, viz. the CustomerID to be updated and a Customer object. That is why you need to append a CustomerID to the URL.

The Delete() Method

public string Delete(string customerId)
{
    HttpResponseMessage response = client.DeleteAsync(this.url + customerId).Result;
    return response.Content.ToString();
}

The Delete() method makes use of the DeleteAsync() method and makes a DELETE request. 

Using WebAPIHelper to Invoke Web API Methods

Now that your helper class is complete, you can use it in the Main() method of the Console Application. Add the following code to test all the methods of WebAPIHelper class.

static void Main(string[] args)
{
    WebAPIHelper helper = new WebAPIHelper("http://localhost:1195/api/customers/");

    //get all Customer items
    Customer[] data = helper.Get();
    foreach (Customer t in data)
    {
        Console.WriteLine(t.CompanyName);
    }

    //get only a single Customer object
    data = helper.Get("ALFKI");
    Console.WriteLine(data[0].CompanyName);

    //modify and save an existing Customer
    data[0].CompanyName = data[0].CompanyName + "123";
    helper.Put(data[0].CustomerID, data[0]);

    //add a new Customer
    Customer c = new Customer();
    c.CustomerID = "CODE1";
    c.CompanyName = "Company 1";
    c.ContactName = "Contact 1";
    c.Country = "Country 1";
    helper.Post(c);

    //delete the Customer we just added
    helper.Delete("CODE1");

    Console.WriteLine("done");
    Console.ReadLine();
} 

Notice the code marked in bold letters. We first create an instance of the WebAPIHelper class by passing the URL of the Web API to it. Depending on your setup you will need to change the port number and / or host of the URL. We then call Get(), Put(), Post() and Delete() methods of the helper class to invoke the respective operations.

To test the application, run the Web API project first and then run the Console Application. The following figure shows a sample run of the Console Application.

A sample run of the Console Application
A sample run of the Console Application

Summary

HttpClient is a modern HTTP client for .NET applications. It allows you to make HTTP requests such as GET, POST, PUT and DELETE in asynchronous manner. The methods GetAsync(), PostAsync(), PutAsync() and DeleteAsync() are used to make the corresponding HTTP requests. In this article you learned the basics of invoking Web API using an HttpClient.

Download the code for this article.

Sitemap | Contact Us