Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# HttpClient로 다른 애플리케이션에서 ASP.NET WebAPI 엔드포인트 호출하는 방법

HttpClient 클래스란?

HttpClient 클래스는 지정된 URL로 HTTP 요청을 전송하고 응답을 수신하기 위한 기본 클래스를 제공합니다. .NET 프레임워크의 비동기(async) 기능을 지원하며, 여러 개의 동시 요청을 효율적으로 처리할 수 있습니다. 내부적으로는 HttpWebRequest와 HttpWebResponse 위에 구현된 추상화 계층으로, 제공되는 모든 메서드가 비동기 방식으로 동작한다는 점이 특징입니다. HttpClient는 System.Net.Http 네임스페이스에서 사용할 수 있습니다.

WebAPI 애플리케이션 만들기

먼저 StudentController와 이에 대응하는 액션 메서드를 포함하는 WebAPI 애플리케이션을 생성해 보겠습니다.

Student 모델

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

Student 컨트롤러

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;
      }
   }
}

C# HttpClient로 다른 애플리케이션에서 ASP.NET WebAPI 엔드포인트 호출하는 방법

C# HttpClient로 다른 애플리케이션에서 ASP.NET WebAPI 엔드포인트 호출하는 방법

콘솔 애플리케이션에서 WebAPI 호출하기

이제 앞서 만든 WebAPI 엔드포인트를 호출하여 학생 정보를 조회하는 콘솔 애플리케이션을 작성해 보겠습니다. HttpClient의 BaseAddress에 API 기본 주소를 설정한 뒤, GetAsync 메서드로 각 엔드포인트에 GET 요청을 보내고 응답 본문을 문자열로 읽어오는 방식입니다.

예제 코드

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}");
            Console.ReadLine();
         }
      }
      private static string GetResponse(string url){
         using (var httpClient = new HttpClient()){
            httpClient.BaseAddress = new Uri("https://localhost:58174/api/");
            var responseTask = httpClient.GetAsync(url);
            var result = responseTask.Result;
            var readTask = result.Content.ReadAsStringAsync();
            return readTask.Result;
         }
      }
   }
}

실행 결과

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"}

실행 결과를 보면 첫 번째 호출에서 전체 학생 목록이 JSON 배열 형태로 반환되고, 두 번째 호출에서는 ID가 2인 학생(John)의 정보만 반환되는 것을 확인할 수 있습니다. 이처럼 HttpClient를 활용하면 완전히 분리된 별도의 애플리케이션에서도 WebAPI의 엔드포인트를 손쉽게 호출하여 데이터를 주고받을 수 있습니다.