How to consume Asp.Net WebAPI endpoints from other applications using C#?

The HttpClient class provides a base class for sending and receiving HTTP requests and responses from URLs. It is a supported async feature of the .NET framework that can process multiple concurrent requests. HttpClient is available in the System.Net.Http namespace and acts as a layer over HttpWebRequest and HttpWebResponse.

This article demonstrates how to consume ASP.NET Web API endpoints from external applications using HttpClient. We'll create a Web API with student data and then consume it from a console application.

Creating the Web API

Student Model

First, let's define the Student model −

namespace DemoWebApplication.Models {
    public class Student {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Student Controller

The controller provides endpoints to retrieve student data −

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace DemoWebApplication.Controllers {
    public class StudentController : ApiController {
        List<Student> students = new List<Student> {
            new Student {
                Id = 1,
                Name = "Mark"
            },
            new Student {
                Id = 2,
                Name = "John"
            }
        };

        public IEnumerable<Student> Get() {
            return students;
        }

        public Student Get(int id) {
            var studentForId = students.FirstOrDefault(x => x.Id == id);
            return studentForId;
        }
    }
}

This creates two endpoints:

  • GET /api/student − Returns all students
  • GET /api/student/{id} − Returns a specific student by ID

Web API Consumer Architecture Console App HttpClient Consumer Web API StudentController Data Provider HTTP GET JSON Response localhost:58174/api/

Consuming the Web API with HttpClient

Basic HttpClient Usage

Here's how to consume the Web API endpoints using HttpClient

using System;
using System.Net.Http;

namespace DemoApplication {
    public class Program {
        static void Main(string[] args) {
            using (var httpClient = new HttpClient()) {
                Console.WriteLine("Calling WebApi for get all students");
                var students = GetResponse("student");
                Console.WriteLine($"All Students: {students}");
                
                Console.WriteLine("Calling WebApi for student id 2");
                var studentForId = GetResponse("student/2");
                Console.WriteLine($"Student for Id 2: {studentForId}");
            }
        }

        private static string GetResponse(string url) {
            using (var httpClient = new HttpClient()) {
                httpClient.BaseAddress = new Uri("http://localhost:58174/api/");
                var responseTask = httpClient.GetAsync(url);
                var result = responseTask.Result;
                var readTask = result.Content.ReadAsStringAsync();
                return readTask.Result;
            }
        }
    }
}

The output of the above code is −

Calling WebApi for get all students
All Students: [{"Id":1,"Name":"Mark"},{"Id":2,"Name":"John"}]
Calling WebApi for student id 2
Student for Id 2: {"Id":2,"Name":"John"}

Using Async/Await Pattern

Improved Asynchronous Implementation

Since HttpClient is designed for asynchronous operations, here's a better implementation using async/await

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace DemoApplication {
    public class Program {
        private static readonly HttpClient httpClient = new HttpClient();

        static async Task Main(string[] args) {
            httpClient.BaseAddress = new Uri("http://localhost:58174/api/");
            
            Console.WriteLine("Calling WebApi for all students (async)");
            var students = await GetResponseAsync("student");
            Console.WriteLine($"All Students: {students}");
            
            Console.WriteLine("Calling WebApi for student id 1 (async)");
            var studentForId = await GetResponseAsync("student/1");
            Console.WriteLine($"Student for Id 1: {studentForId}");
        }

        private static async Task<string> GetResponseAsync(string url) {
            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }
    }
}

The output of the above code is −

Calling WebApi for all students (async)
All Students: [{"Id":1,"Name":"Mark"},{"Id":2,"Name":"John"}]
Calling WebApi for student id 1 (async)
Student for Id 1: {"Id":1,"Name":"Mark"}

Key Best Practices

Practice Description
Reuse HttpClient Create a single HttpClient instance and reuse it to avoid socket exhaustion.
Use Async Methods Always use GetAsync(), PostAsync() etc. instead of blocking calls.
Handle Errors Use EnsureSuccessStatusCode() or check IsSuccessStatusCode property.
Set Base Address Configure BaseAddress once rather than using full URLs repeatedly.

Conclusion

HttpClient provides a powerful and flexible way to consume ASP.NET Web API endpoints from external applications. Always prefer the asynchronous methods and reuse HttpClient instances for optimal performance. The async/await pattern ensures your application remains responsive while making HTTP calls.

Updated on: 2026-03-17T07:04:36+05:30

467 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements