.NET 调用 RESTful API 并处理 JSON 是常见的开发任务,通常使用 HttpClient 发起请求,配合 System.Text.Json 解析返回的 JSON 数据。下面是一个清晰、实用的实现方式。
1. 使用 HttpClient 发起 GET 请求
推荐将 HttpClient 作为单例或通过依赖注入使用,避免频繁创建导致资源浪费。
示例:获取用户信息using System.Net.Http.Json;
<p>var httpClient = new HttpClient();
try
{
var response = await httpClient.GetFromJsonAsync<User>("<a href="https://www.php.cn/link/a89ab5f7e8a7f0419b5d07e00c521668">https://www.php.cn/link/a89ab5f7e8a7f0419b5d07e00c521668</a>");
if (response != null)
{
Console.WriteLine($"用户名: {response.Name}");
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"请求失败: {e.Message}");
}</p>2. 定义匹配 JSON 结构的数据类
确保 C# 类的属性与 JSON 字段对应,可使用 [JsonPropertyName] 指定映射关系。
using System.Text.Json.Serialization;
<p>public class User
{
public int Id { get; set; }</p><pre class="brush:php;toolbar:false;">[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" };
<p>var response = await httpClient.PostAsJsonAsync("<a href="https://www.php.cn/link/93a819cbd635bd1505ef0f804c21cc2a">https://www.php.cn/link/93a819cbd635bd1505ef0f804c21cc2a</a>", newUser);</p><p>if (response.IsSuccessStatusCode)
{
var createdUser = await response.Content.ReadFromJsonAsync<User>();
Console.WriteLine($"创建成功,ID: {createdUser.Id}");
}</p>4. 错误处理与状态码判断
不要忽略 HTTP 状态码,合理处理 4xx 和 5xx 错误。
使用 EnsureSuccessStatusCode() 自动抛出异常(可选) 或手动检查 response.IsSuccessStatusCode 读取错误响应体时可用 ReadAsStringAsync()var response = await httpClient.GetAsync("https://api.example.com/data");
<p>if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"错误: {response.StatusCode}, 内容: {errorContent}");
return;
}</p><p>var data = await response.Content.ReadFromJsonAsync<DataType>();</p>基本上就这些。只要配置好类型映射,用 HttpClient + System.Text.Json 就能高效完成调用和解析。
