Self-hosting means running our ASP.NET Web API project on our own Web Server rather than using IIS. Here, we are not building a complete HTTP Web Server either. We’re simply using the functionality.
Introduction
This blog shows the walkthrough of how to call a Web API from a client application which we have created earlier.
Let's 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.
nuget package manager is: Install-Package Microsoft.AspNet.WebApi.SelfHost -Version 5.2.7
Step 3
Now, add a reference in TestClient to the SampleSelfHost project.
In Solution Explorer, right-click the ClientApp project and select "Add Reference". In the "Reference Manager" dialog, under Solution, select Projects. Select the SelfHost project. Click "OK".
Step 4
Now, open the Program.cs file and add the following implementation. Then, run the project by setting it as a startup 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() {
-
- HttpResponseMessage resp = client.GetAsync("api/students").Result;
-
- 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();
-
- var students = resp.Content.ReadAsAsync < IEnumerable < SampleSelfHost.Student >> ().Result;
- foreach(var student in students) {
- Console.WriteLine(student.Name);
- }
- }
- }
- }
Conclusion
In this blog, we have learned how to call a Web API from a console application.