Consume Web API in a .NET C# client

Recently I have written a console client in C# to consume those web services developed in my previous post by using APS.NET Web API 2 and Microsoft Entity Framework 6.

I started with a new Console Application (called WebApiClient) in C# in Visual Studio 2013, and then installed the Microsoft ASP.NET Web API Class Libraries using NuGet. Lastly, I added Employee.cs (model class) which was used by web services as my data structure.

The following is a web client program in C# (Program.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace WebApiClient
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            string baseUrl = "http://localhost:55142";
            client.BaseAddress = new Uri(baseUrl);
            
            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            //New Employee Record URL
            int anEmpId = -1;
            string serviceUrl;


            // 1. Post a new employee
            serviceUrl="api/employee";
            Console.WriteLine("1. Add an employee by sending POST {0}/{1}  \r\n", baseUrl, serviceUrl);
            Console.WriteLine("The following new employee is added  \r\n");
            var anEmployee = new Employee() { 
                lastname = "Smith",
                firstname = "Adam",
                title = "Economist",
                titleofcourtesy = "Dr.",
                birthdate = Convert.ToDateTime("1958-12-05 "),
                hiredate = Convert.ToDateTime("1990-01-01"),
                address = "188 Bay Street",
                city = "London",
                region = "",
                postalcode = "A1B 2Z3",
                country = "UK",
                phone = "(71) 234-8228",
                mgrid = 1};
            

            HttpResponseMessage response = client.PostAsJsonAsync(serviceUrl, anEmployee).Result;
            if  (response.IsSuccessStatusCode)
            {

                // display the new employee
                Console.WriteLine("firstname={0}", anEmployee.firstname);
                Console.WriteLine("lastname={0}", anEmployee.lastname);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            Console.WriteLine("\r\nCheck your database table. Press any key to continue...\r\n");
            Console.ReadKey();


            // 2. Get all employees.
            serviceUrl="api/employee";
            Console.WriteLine("2. Get All Employee by sending GET {0}/{1} \r\n", baseUrl, serviceUrl);

            response = client.GetAsync(serviceUrl).Result;        // Blocking call!
            if  (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var employees = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result;
                foreach (var e in employees)
                    {
                         
                        if (e.firstname.Equals("Adam") & e.lastname.Equals("Smith"))
                        { 
                            anEmpId = e.empid;
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("{0};\t{1};\t{2};\t{3}", e.empid, e.firstname, e.lastname, e.title);
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("\r\nThe new employee is with empid={0}\r\n", anEmpId);
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }
                        else
                        {
                            Console.WriteLine("{0};\t{1};\t{2};\t{3}", e.empid, e.firstname, e.lastname, e.title);
                        }
                    }
            }
            else
            {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            Console.WriteLine("\r\nPress any key to continue...\r\n");
            Console.ReadKey();

            // 3. Get an employee by empid
            if (anEmpId>0)
            {
                serviceUrl = "api/employee/" + anEmpId.ToString();

            }
            else
            {
                serviceUrl = "api/employee/1";
                anEmpId = 1;
            }

            Console.WriteLine("3. Get the employee with empid={0} by sending GET {1}/{2} \r\n", anEmpId, baseUrl, serviceUrl);

            response = client.GetAsync(serviceUrl).Result;        // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var a_employee = response.Content.ReadAsAsync<Employee>().Result;

                Console.WriteLine("emid={0}", a_employee.empid);
                Console.WriteLine("FirstName={0}", a_employee.firstname);
                Console.WriteLine("LastName={0}", a_employee.lastname);
                Console.WriteLine("Title={0}", a_employee.title);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            Console.WriteLine("\r\nPress any key to continue...\r\n");
            Console.ReadKey();

            // 4. Update an employee by empid
            Console.WriteLine("4. Update an employee with empid = {0} by sending PUT {1}/{2} \r\n", anEmpId, baseUrl, serviceUrl);

            response = client.GetAsync(serviceUrl).Result;        // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Retrieve the record first
                var a_employee = response.Content.ReadAsAsync<Employee>().Result;
                Console.WriteLine("The record is retrieved before update: \r\n");
                Console.WriteLine("emid={0}", a_employee.empid);
                Console.WriteLine("FirstName={0}", a_employee.firstname);
                Console.WriteLine("LastName={0}", a_employee.lastname);
                Console.WriteLine("Title={0}", a_employee.title);

                // Update the tile field of the record
                a_employee.title = "Senior Economist";

                response = client.PutAsJsonAsync(serviceUrl, a_employee).Result;

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("\r\nThe record with empid={0} was updated with the following: \r\n", anEmpId);
                    Console.ForegroundColor = ConsoleColor.Yellow; 
                    Console.WriteLine("Title={0}", a_employee.title);
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            Console.WriteLine("\r\nCheck your database table. Press any key to continue...\r\n");
            Console.ReadKey();

            // 5. delete an employee added in step 1
            Console.WriteLine("4. Delete an employee with empid = {0} by sending DELETE {1}/{2} \r\n", anEmpId, baseUrl, serviceUrl);

            response = client.DeleteAsync(serviceUrl).Result;
             if (response.IsSuccessStatusCode)
             {
                 Console.ForegroundColor = ConsoleColor.Yellow;
                 Console.WriteLine("The record with empid={0} was deleted.", anEmpId);
                 Console.ForegroundColor = ConsoleColor.Gray;
             }
             else
             {
                 Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
             }
             Console.WriteLine("\r\nCheck your database table.\r\n");
        }
    }
}

About henry416
I am a computer technology explorer and an university student based on Toronto. If you have any question, please feel free to discuss and comment here

3 Responses to Consume Web API in a .NET C# client

  1. Dean Goddard says:

    Can you please extend the sample “Consume Web API in a .NET C# client” to include security by registering and/or logging in, to a Web API service with ASP.NET Identity, and using a token for subsequent calls. I can’t find any examples of this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s