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

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

.net怎么调用一个restful api并处理返回的json

.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}");
}

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>
                    <div class="aritcle_card">
                        <a class="aritcle_card_img" href="/ai/1675">
                            <img src="https://img.php.cn/upload/ai_manual/000/969/633/68b6d5b124798234.png" alt="百度文心百中">
                        </a>
                        <div class="aritcle_card_info">
                            <a href="/ai/1675">百度文心百中</a>
                            <p>百度大模型语义搜索体验中心</p>
                            <div class="">
                                <img src="/static/images/card_xiazai.png" alt="百度文心百中">
                                <span>263</span>
                            </div>
                        </div>
                        <a href="/ai/1675" class="aritcle_card_btn">
                            <span>查看详情</span>
                            <img src="/static/images/cardxiayige-3.png" alt="百度文心百中">
                        </a>
                    </div>
                <p>if (response.IsSuccessStatusCode)
{
var createdUser = await response.Content.ReadFromJsonAsync<User>();
Console.WriteLine($"创建成功,ID: {createdUser.Id}");
}

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>();

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

以上就是.NET怎么调用一个RESTful API并处理返回的JSON的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。