Consume ASP.Net Web API Using HttpClient in WPF

In this article you will learn how to consume a Web API using HttpClient in WPF.

What is HttpClient? It provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

Getting Started

Start Visual Studio 2012 and create a WPF Application and provide a name of the project.

img1.jpg

Image 1.

Now right-click on the solution and click on "Manage NuGet Packages".

img2.jpg

Image 2.

Search for HttpClient in the online packages and click "Install" for "Microsoft HTTP Client Libraries".

img3.jpg

Image 3.

After installing you will see that there are a couple of assemblies that have been added to the project references.

img4.jpg

Image 4.

This is my Web API URL:

http://localhost:12789/api/employee

And this is the API result set.

img5.jpg

Image 5.

img6.jpg

Image 6.

Now add one more reference using the NuGet package manager.

img7.jpg

Image 7.

Now let's consume this Web API in the Data Grid and write code for adding a new record, searching and deleting.

First of all add a data grid control and a few labels, textboxes and buttons.

<Window x:Class="ConsumeWebAPIUsingHttpClientInWPF.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="500" Width="525" Loaded="Window_Loaded">

    <Grid Margin="10,0,2,289">

        <DataGrid HorizontalAlignment="Left" VerticalAlignment="Top" x:Name="grdEmployee" />

        <Label Content="Id" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="18,203,0,-67"/>

        <Label Content="Name" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="18,245,0,-103"  />

        <Label Content="Address" HorizontalAlignment="Left" VerticalAlignment="Top"  Margin="18,276,0,-136" />

        <Label Content="Designation" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="18,314,0,-176"  />

        <Button Content="Delete" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="342,203,0,-70" x:Name="btnDelete" Click="btnDelete_Click" />

        <TextBox HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="125,203,0,-56" x:Name="txtId"  />

        <TextBox HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="125,234,0,-92" x:Name="txtName"  />

        <TextBox HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="125,279,0,-136" x:Name="txtAddress"  />

        <TextBox HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="125,316,0,-176" x:Name="txtDesignation"  />

        <Button Content="Search" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" x:Name="btnSearch" Click="btnSearch_Click" Margin="250,203,0,-59" Height="Auto"  />

        <Button Content="Add New" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" x:Name="btnAdd" Click="btnAdd_Click" Margin="125,363,0,-219" Height="Auto"/>

 

    </Grid>

</Window>

Now let's work on the code behind. First we will fetch the all employees list from the Web API.

Add these are the namespaces.

using System.Net.Http;
using System.Net.Http.Headers;

private void BindEmployeeList()
{
    HttpClient client = new HttpClient();
    client.BaseAddress =
new Uri("http://localhost:12789/");
    
//client.DefaultRequestHeaders.Add("appkey", "myapp_key");
    client.DefaultRequestHeaders.Accept.Add(
      
new MediaTypeWithQualityHeaderValue("application/json"));
 
    
HttpResponseMessage response = client.GetAsync("api/employee").Result;
    if (response.IsSuccessStatusCode)
    {
        
var employees = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result;
        grdEmployee.ItemsSource = employees;

    }
    
else
    {
        
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
    }

}

private void Window_Loaded(object sender, RoutedEventArgs e)

{

    BindEmployeeList();

}

img8.jpg

Image 8.

Now let's add a new employee.

private void btnAdd_Click(object sender, RoutedEventArgs e)

{

    HttpClient client = new HttpClient();

    client.BaseAddress = new Uri("http://localhost:12789/");

 

    client.DefaultRequestHeaders.Accept.Add(

       new MediaTypeWithQualityHeaderValue("application/json"));           

    var employee = new Employee();

 

    employee.Id = int.Parse(txtId.Text);

    employee.Name = txtName.Text;

    employee.Address = txtAddress.Text;

    employee.Designation = txtDesignation.Text;

 

    var response = client.PostAsJsonAsync("api/employee", employee).Result;

 

    if (response.IsSuccessStatusCode)

    {

        MessageBox.Show("Employee Added");

        txtId.Text = "";

        txtName.Text = "";

        txtAddress.Text = "";

        txtDesignation.Text = "";

        BindEmployeeList();

    }

    else

    {

        MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);

    }

}

img9.jpg

Image 9.

Fill in the information and click the "Add New" button.

img10.jpg

Image 10.

You will see that the record has been added to the data grid.

Now let's work on deleting a record.

private void btnDelete_Click(object sender, RoutedEventArgs e)

{

    HttpClient client = new HttpClient();

    client.BaseAddress = new Uri("http://localhost:12789/");

 

    var id = txtId.Text.Trim();

 

    var url = "api/employee/" + id;

 

    HttpResponseMessage response = client.DeleteAsync(url).Result;

 

    if (response.IsSuccessStatusCode)

    {

        MessageBox.Show("User Deleted");

         BindEmployeeList();

     }

    else

    {

        MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);

    }

}

img11.jpg

Image 11.

Enter an id in the id TextBox and click the delete button.

img12.jpg

Image 12.

As you can see record number 7 has been deleted.

Now let's work on the search part.

private void btnSearch_Click(object sender, RoutedEventArgs e)

{

    HttpClient client = new HttpClient();

    client.BaseAddress = new Uri("http://localhost:12789/");

 

    client.DefaultRequestHeaders.Accept.Add(

        new MediaTypeWithQualityHeaderValue("application/json"));

 

    var id = txtId.Text.Trim();

 

    var url = "api/employee/" + id;

 

    HttpResponseMessage response = client.GetAsync(url).Result;

 

    if (response.IsSuccessStatusCode)

    {
       
var employees = response.Content.ReadAsAsync<Employee>().Result;
       
MessageBox.Show("Employee Found : " + employees.Name + " " + employees.Address + " " + employees.Designation);
    }
    else
    {
        
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase); 

    }

}

img13.jpg

Image 13.

Enter an id in the text box and click the "Search" button.