如何使用 C# 從其他應用程式使用 Asp.Net WebAPI 端點?
HttpClient 類提供了一個基本類,用於傳送/接收 URL 的 HTTP 請求/響應。它是 .NET 框架支援的非同步功能。HttpClient 能夠處理多個併發請求。它是 HttpWebRequest 和 HttpWebResponse 之上的一層。HttpClient 的所有方法都是非同步的。HttpClient 在 System.Net.Http 名稱空間中可用。
讓我們建立一個 WebAPI 應用程式,其中包含一個 StudentController 和相應的操作方法。
學生模型
namespace DemoWebApplication.Models{ public class Student{ public int Id { get; set; } public string Name { get; set; } } }
學生控制器
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; } } }
現在,讓我們建立一個控制檯應用程式,我們希望使用上面建立的 WebApi 端點來獲取學生詳細資訊。
示例
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: {students}"); Console.ReadLine(); } } private static string GetResponse(string url){ using (var httpClient = new HttpClient()){ httpClient.BaseAddress = new Uri("https://: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"}
在上面的示例中,我們可以看到 WebApi 的端點是從一個單獨的控制檯應用程式呼叫的。
廣告