Learn Self Host of a Web API( Call the Web API from a Client Application (C#)) Part 2

Rama Sagar
Posted by in ASP.NET Web API category on for Beginner level | Points: 250 | Views : 2931 red flag

Self hosting means running our ASP.Net Web API project in our own Web Server rather than via IIS. Here we are not building a complete Http Web server either. We’re simply using functionality.

Introduction


This article shows the walk through of how to call a Web API from a Client Application which we have created in Part 1


Lets start by creating a simple console Application to the existing Solution which we have created

  •   Step 1    Right click the Solution Explorer and select add New Project    






  • Step 2 : Install  Microsoft.AspNet.WebApi.SelfHost through Packager Manager console as shown below
  •          Click on Tools--->Select Library Package Manager-->Package Manager Console and Type the following command

   


   Install-Package Microsoft.AspNet.WebApi.SelfHost





            
  • Step 3: Now add a reference in TestClient to the SampleSelfHost project
     In Solution Explorer-->right-click the ClientApp project--->Select Add Reference.

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



  • Step 4: Now open Program.cs file and add the following Implementation and run the project by setting as 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");

            ListAllStudents();
            ListStudent(1);
            ListStudents("seventh");

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

        static void ListAllStudents()
        {
            //Call HttpClient.GetAsync to send a GET request to the appropriate URI

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

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

            resp.EnsureSuccessStatusCode();

           var students = resp.Content.ReadAsAsync<IEnumerable<SampleSelfHost.Student>>().Result;
            foreach (var p in students)
            {
                Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Standard, p.Marks);
            }
        }

        static void ListStudent(int id)
        {
            var resp = client.GetAsync(string.Format("api/students/{0}", id)).Result;
            resp.EnsureSuccessStatusCode();

            var student = resp.Content.ReadAsAsync<SampleSelfHost.Student>().Result;
            Console.WriteLine("ID {0}: {1}", id, student.Name);
        }

        static void ListStudents(string standard)
        {
            Console.WriteLine("Students in '{0}':", standard);

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

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

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

           var students = resp.Content.ReadAsAsync<IEnumerable<SampleSelfHost.Student>>().Result;
            foreach (var student in students)
            {
                Console.WriteLine(student.Name);
            }
        }

    }
}
 

Conclusion


In this article we have learned how to call a web API from a console Application 


Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)