Coding Paradox

Blog On .Net, CSharp, Windows Phone Programming

Calling ASP.Net WebAPI using HttpClient

without comments

In this post, we are going to learn how to call an ASP.Net WebAPI using HttpClient libraries. The HttpClient Library is quite useful and can be used while calling your WebAPI from Windows applications, Console Applications or even Windows 8 applications.

We will use the same WebAPI which we created in my previous post “Using ASP.Net WebAPI with WebForms” but this time we will consume it from a WPF application.

Create A WPF Application Project

Open Visual Studio 2012, Go To New -> Project. Select Visual C# -> Windows from the left hand navigation and select project type as WPF Application. Enter the project name as WebAPIClient.

Installing WebAPI Client Libraries

We will then add the HttpClient libraries in our project using the NuGet Package Manager which makes it very easy to install the libraries in our project

In the Tools menu, select Library Package Manager -> Manage NuGet Packages For Solution

In the Manage NuGet Packages dialog box which opens, select online and search for “Http Client” and select the Microsoft Http Client Libraries which appear as shown below

Select Install and it will ask you to select the project in which you want to install it. Click on Ok and close the dialog once the installation is done.

Similarly also install the package “JSON.Net” from Nuget Package Manager.

Creating The User Interface

We will add a DataGrid to display the user information and we will also create a simple form of textbox and button to get data from the user and add it through the API

Here is how the code for MainWindows.xaml will look like

Here is how our UI will look like


Create Model Class

We will create a Model class called “Users.cs” which will be used by HttpClient libraries to read and write the data to the WebAPI.

Creating HTTP Client

We have created a GetData() function which will call the WebAPI using the Client library and get a list of users and bind it to the Data Grid (Include a reference to System.Net.Http.Formatting assembly in the project)

In this function, we are creating a new instance of the HttpClient and setting its base address to “http://localhost:56851” . This should be the address where our API is running. You can change the port number to match the port at which your API which you created in the previous tutorial runs.

We are then setting the Accept header property to “application/json” which instructs the server to send the response in Json format.

We the call the “GetAsync” method which sends a HTTP Get request to “api/User”. It is an asynchronous method which will return immediately without waiting for response from the server. It returns a Task object and we can use the “Result” property of the Task class to get the response. ( As we are using the Result property, we are turning it into a blocking call as it will wait for a response. It is not a good practice to follow in case of working with Windows applications, but to keep the example simple we will continue with it. For Real projects, it is better to use Non Blocking calls to ensure that your UI is always active )

We then check whether response to see if it indicated success. In case of success, the response will contains our data in JSON format.

We then call the “ReadAsAsync()” method which deserializes the response body to our Users type. This method is also asynchronous but using the Result property makes it a blocking call. We then bind the result to our DataGrid and it is displayed on the screen.

Please Make Sure you are running the Web API from my previous post for it to work.

On running the application, you will get the following screen.

Adding A User (POST)

On the Add User button click, we call the following code to Add a User

We again create a client object passing the base address and setting the headers. We then create a Users object collecting information from the textbox.

We call the “PostAsJsonAsync” method of the library and pass the user object which we have created. If a success response is returned, the user is successfully added and we refresh the DataGrid.

Searching For a User

Here is the code which gets called on the search button click

The code is similar to the Get Request which we used earlier. This time while constructing the URL, we are also passing the “id” of the user to the API.

While reading the response, we are using a single User object as a single user will be returned. If no user is found based on the id, an Http Response Exception is thrown by our WebAPI.


Deleting a User

Here is code which we are calling on Delete Button Click

This is similar to the Search User code. We create the URL by passing the Id of the user which we want to delete.

We then call the “DeleteAsync” method of the library which will delete the User with the specified id. If no user is found, an exception will be thrown.

Hope you enjoyed reading the Article. Let me know in comments if you face any error.

Please make sure to run the WebAPI Demo project before running the WPF application

Download Solution

Download WebAPI Solution

Written by Mako

February 24th, 2013 at 8:12 pm

Posted in ASP.Net,C#,WebAPI

Tagged with , ,