编辑
2025-11-23
C#
00

目录

REST API基础概念
常见REST API交互模式
请求-响应模式
批量处理模式
分页模式
认证与授权
总结

REST API作为现代网络应用的标准交互方式,在微服务架构和前后端分离的开发模式中扮演着核心角色。本文将深入探讨REST API的交互模式,并结合C#实现详细示例,帮助你掌握这一关键技术。

REST API基础概念

REST (Representational State Transfer) 是一种架构风格,而非协议。它基于以下原则:

  1. 资源标识:通过URI唯一标识资源
  2. 统一接口:使用标准HTTP方法操作资源
  3. 无状态通信:每个请求包含所有必要信息
  4. 资源表述:资源可以有多种表现形式(JSON/XML等)

常见REST API交互模式

请求-响应模式

最基本的交互模式,客户端发送请求,服务端返回响应。

C#
using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; namespace AppREST { internal class Program { static async Task Main(string[] args) { var product = await GetProductAsync(1); Console.WriteLine($"产品名称: {JsonSerializer.Serialize(product)}"); Console.ReadKey(); } // 使用HttpClient发起GET请求示例 static async Task<Product> GetProductAsync(int id) { // 创建HttpClient实例 using (HttpClient client = new HttpClient()) { // 设置基础地址和默认请求头 client.BaseAddress = new Uri("https://localhost:7283/api/"); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // 发送GET请求并获取响应 HttpResponseMessage response = await client.GetAsync($"products/{id}"); // 检查响应状态码 if (response.IsSuccessStatusCode) { // 反序列化JSON响应为Product对象 var product = await response.Content.ReadFromJsonAsync<Product>(); return product; } else { // 处理错误情况 throw new HttpRequestException($"获取产品失败: {response.StatusCode}"); } } } } }

image.png

批量处理模式

一次请求处理多个资源,减少网络往返。

C#
using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; using System.Text.Json; namespace AppREST { internal class Program { static async Task Main(string[] args) { var products = await CreateProductsAsync(new List<Product> { new Product { Name = "iPhone 14 Pro", Price = 999.99m, StockQuantity = 50 }, new Product { Name = "Samsung Galaxy S23", Price = 899.99m, StockQuantity = 30 }}); Console.WriteLine($"产品名称: {JsonSerializer.Serialize(products)}"); Console.ReadKey(); } // 批量创建产品示例 static async Task<IEnumerable<Product>> CreateProductsAsync(List<Product> products) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:7283/api/"); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // 将产品列表序列化为JSON var productJson = JsonSerializer.Serialize(products); var content = new StringContent(productJson, Encoding.UTF8, "application/json"); // 发送POST请求 HttpResponseMessage response = await client.PostAsync("products/batch", content); if (response.IsSuccessStatusCode) { // 反序列化响应内容 var createdProducts = await response.Content.ReadFromJsonAsync<List<Product>>(); return createdProducts; } else { throw new HttpRequestException($"批量创建产品失败: {response.StatusCode}"); } } } } }

image.png

分页模式

处理大量数据时,分批次返回结果。

C#
using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; using System.Text.Json; namespace AppREST { internal class Program { static async Task Main(string[] args) { var products = await GetProductsPagedAsync(1,2); Console.WriteLine($"产品名称: {JsonSerializer.Serialize(products)}"); Console.ReadKey(); } // 获取分页产品列表 static async Task<List<Product>> GetProductsPagedAsync(int pageNumber, int pageSize) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:7283/api/"); // 构建带分页参数的URL var response = await client.GetAsync($"products?page={pageNumber}&pageSize={pageSize}"); if (response.IsSuccessStatusCode) { // 反序列化分页结果 var result = await response.Content.ReadFromJsonAsync<List<Product>>(); return result; } else { throw new HttpRequestException($"获取分页产品失败: {response.StatusCode}"); } } } } }

image.png

认证与授权

实现基于令牌的身份验证。其实区别就是Bearer这个,在请求头中可以找到。

C#
// 使用JWT令牌认证的API请求 public async Task<UserProfile> GetUserProfileAsync(string token) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("https://api.example.com/"); // 添加认证令牌到请求头 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = await client.GetAsync("users/profile"); if (response.IsSuccessStatusCode) { return await response.Content.ReadFromJsonAsync<UserProfile>(); } else if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException("访问未授权,请重新登录"); } else { throw new HttpRequestException($"获取用户资料失败: {response.StatusCode}"); } } }

总结

REST API交互模式是现代网络开发的核心技术,掌握它能够帮助我们构建高效、可扩展、安全的Web应用。在C#生态系统中,ASP.NET Core提供了强大的工具和框架支持REST API的开发和消费。

本文详细介绍了REST API的基本原则、常见交互模式、实现技术、最佳实践和安全考量。通过学习这些知识并应用示例代码,你将能够设计和实现符合行业标准的REST API,满足各种复杂业务场景的需求。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!