.NET怎么调用一个RESTful API并处理返回的JSON

使用HttpClient调用RESTful API并结合System.Text.Json处理JSON数据,通过定义匹配JSON结构的C#类,可高效实现GET/POST请求、响应解析及错误处理。

.NET 调用 RESTful API 并处理 JSON 是常见的开发任务,通常使用 HttpClient 发起请求,配合 System.Text.Json 解析返回的 JSON 数据。下面是一个清晰、实用的实现方式。

1. 使用 HttpClient 发起 GET 请求

推荐将 HttpClient 作为单例或通过依赖注入使用,避免频繁创建导致资源浪费。

示例:获取用户信息

using System.Net.Http.Json;

var httpClient = new HttpClient(); try { var response = await httpClient.GetFromJsonAsync("https://www./link/a89ab5f7e8a7f0419b5d07e00c521668"); if (response != null) { Console.WriteLine($"用户名: {response.Name}"); } } catch (HttpRequestException e) { Console.WriteLine($"请求失败: {e.Message}"); }

2. 定义匹配 JSON 结构的数据类

确保 C# 类的属性与 JSON 字段对应,可使用 [JsonPropertyName] 指定映射关系。

using System.Text.Json.Serialization;

public class User { public int Id { get; set; }

[JsonPropertyName("name")]
public string Name { get; set; }

[JsonPropertyName("email")]
public string Email { get; set; }

}

3. 处理 POST 请求并发送 JSON

使用 PostAsJsonAsync 自动序列化对象为 JSON 并提交。

var newUser = new User { Name = "张三", Email = "zhangsan@example.com" };

var response = await httpClient.PostAsJsonAsync("https://www./link/93a819cbd635bd1505ef0f804c21cc2a", newUser);

if (response.IsSuccessStatusCode) { var createdUser = await response.Content.ReadFromJsonAsync(); Console.WriteLine($"创建成功,ID: {createdUser.Id}"); }

4. 错误处理与状态码判断

不要忽略 HTTP 状态码,合理处理 4xx 和 5xx 错误。

  • 使用 EnsureSuccessStatusCode() 自动抛出异常(可选)
  • 或手动检查 response.IsSuccessStatusCode
  • 读取错误响应体时可用 ReadAsStringAsync()

var response = await httpClient.GetAsync("https://api.example.com/data");

if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"错误: {response.StatusCode}, 内容: {errorContent}"); return; }

var data = await response.Content.ReadFromJsonAsync();

基本上就这些。只要配置好类型映射,用 HttpClient + System.Text.Json 就能高效完成调用和解析。