Understanding How to Call the Web API From a Client Application (C#): Part 2

Introduction

This article provides a walkthrough of how to call a Web API from a client application that we created in Part 1.
 
Let's start by creating a simple Console Application in the existing solution that we have already created.

Step 1: Right-click the Solution Explorer, select "Add New Project" and select "Console Application".

Add New Project
 
Step 2: Install Microsoft.AspNet.WebApi.SelfHost using the Packager Manager console as shown below. Click on "Tools" then select "Library Package Manager" --> "Package Manager Console" and enter the following command:

Package Manager Console
 
Install-Package Microsoft.AspNet.WebApi.SelfHost

Install-Package
 
Step 3: Now add a reference to the TestClient to the SelfHost1 project as in the following:

In Solution Explorer right-click the ClientApp project then select "Add Reference".

In the Reference Manager dialog, under "Solution", select "Projects". Select the SelfHost project. Click "OK" as shown below.

SelfHost project
 
Step 4: Now open the Program.cs file and add the following implementation. Then run the project by setting TestClient as the Start up project.

using System;  

using System.Collections.Generic;  

using System.Net.Http;  

  

namespace TestClient  

{  

    class Program  

    {  

        static HttpClient client = new HttpClient();    

        static void Main(string[] args)  

        {  

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

            ListAllBooks();  

            ListBook(1);  

            ListBooks("seventh");    

            Console.WriteLine("Press Enter to quit.");  

            Console.ReadLine();  

        }  

  

        static void ListAllBooks()  

        {  

            //Call HttpClient.GetAsync to send a GET request to the appropriate URI   

            HttpResponseMessage resp = client.GetAsync("api/books").Result;  

            //This method throws an exception if the HTTP response status is an error code.  

            resp.EnsureSuccessStatusCode();    

            var books = resp.Content.ReadAsAsync<IEnumerable<SelfHost1.book>>().Result;  

            foreach (var p in books)  

            {  

                Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Author, p.Rating);  

            }  

        }  

        static void ListBook(int id)  

        {  

            var resp = client.GetAsync(string.Format("api/books/{0}", id)).Result;  

            resp.EnsureSuccessStatusCode();  

  

            var book1 = resp.Content.ReadAsAsync<SelfHost1.book>().Result;  

            Console.WriteLine("ID {0}: {1}", id, book1.Name);  

        }    

        static void ListBooks(string author)  

        {  

            Console.WriteLine("Books in '{0}':", author);    

            string query = string.Format("api/books?author={0}", author);    

            var resp = client.GetAsync(query).Result;  

            resp.EnsureSuccessStatusCode();    

            //This method is an extension method, defined in System.Net.Http.HttpContentExtensions    

            var books = resp.Content.ReadAsAsync<IEnumerable<SelfHost1.book>>().Result;  

            foreach (var book in books)  

            {  

                Console.WriteLine(book.Name);  

            }  

        }    

    }  

}   

Summary

In this article, I explained how to  call a Web API from a client application.

Up Next
    Ebook Download
    View all
    Learn
    View all