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

.NET 调用 RESTful API 并处理 JSON 是常见的开发任务,通常使用 HttpClient 发起请求,配合 System.Text.Json 解析返回的 JSON 数据。下面是一个清晰、实用的实现方式。
推荐将 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}");
}确保 C# 类的属性与 JSON 字段对应,可使用 [JsonPropertyName] 指定映射关系。
using System.Text.Json.Serialization;
<p>public class User
{
public int Id { get; set; }</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("email")]
public string Email { get; set; }}
使用 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>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1371">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680247950195.png" alt="Find JSON Path Online">
</a>
<div class="aritcle_card_info">
<a href="/ai/1371">Find JSON Path Online</a>
<p>Easily find JSON paths within JSON objects using our intuitive Json Path Finder</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="Find JSON Path Online">
<span>30</span>
</div>
</div>
<a href="/ai/1371" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="Find JSON Path Online">
</a>
</div>
<p>if (response.IsSuccessStatusCode)
{
var createdUser = await response.Content.ReadFromJsonAsync<User>();
Console.WriteLine($"创建成功,ID: {createdUser.Id}");
}不要忽略 HTTP 状态码,合理处理 4xx 和 5xx 错误。
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>();基本上就这些。只要配置好类型映射,用 HttpClient + System.Text.Json 就能高效完成调用和解析。
以上就是.NET怎么调用一个RESTful API并处理返回的JSON的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号