如何在C#中向其他API发送带字符串参数的HTTP Post请求并保存响应实体?
C# 发送带参HTTP请求并将响应解析为实体对象
1. 定义响应实体类
首先根据第三方API的响应结构,创建匹配的C#实体类。假设API返回的JSON结构如下:
{ "Id": 123, "Username": "john_doe", "Email": "john@example.com", "IsActive": true }
对应的实体类(使用System.Text.Json序列化):
using System.Text.Json.Serialization; public class ApiResponse { [JsonPropertyName("Id")] public int Id { get; set; } [JsonPropertyName("Username")] public string Username { get; set; } [JsonPropertyName("Email")] public string Email { get; set; } [JsonPropertyName("IsActive")] public bool IsActive { get; set; } }
如果用Newtonsoft.Json(Json.NET),只需将JsonPropertyName替换为JsonProperty即可。
2. 使用HttpClient发送请求(官方推荐)
HttpClient是.NET官方推荐的HTTP客户端,注意复用实例(避免每次请求新建实例导致socket资源耗尽)。
2.1 GET请求(带字符串查询参数)
向目标API发送带查询参数的GET请求:
using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using System.Web; // 用于QueryHelpers,ASP.NET Core项目需安装Microsoft.AspNetCore.WebUtilities包 public async Task<ApiResponse> GetUserByUsername(string username) { // 实际项目中建议通过依赖注入复用HttpClient实例,而非直接new using var httpClient = new HttpClient(); // 规范构建带编码参数的请求地址 var requestUri = HttpUtility.ParseQueryString(string.Empty); requestUri["username"] = username; var fullUri = new Uri($"https://api.example.com/user?{requestUri}"); var response = await httpClient.GetAsync(fullUri); // 校验请求状态,非2xx状态码直接抛出异常 response.EnsureSuccessStatusCode(); // 将响应JSON解析为实体对象 return await response.Content.ReadFromJsonAsync<ApiResponse>(); }
2.2 POST请求(带字符串参数的JSON请求体)
如果参数需要放在请求体中(比如登录请求),先定义请求参数实体:
public class LoginRequest { public string Username { get; set; } public string Password { get; set; } }
然后发送POST请求:
public async Task<ApiResponse> Login(string username, string password) { using var httpClient = new HttpClient(); var loginPayload = new LoginRequest { Username = username, Password = password }; // 自动将实体序列化为JSON请求体发送 var response = await httpClient.PostAsJsonAsync("https://api.example.com/login", loginPayload); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync<ApiResponse>(); }
3. 关键注意事项
- HttpClient复用:ASP.NET Core项目中,通过
AddHttpClient()注册到依赖注入容器,实现全局复用;控制台/桌面项目可创建静态单例实例。 - 参数编码:GET请求的查询参数必须编码,避免特殊字符(如空格、&)破坏请求结构,用
HttpUtility或QueryHelpers处理更安全。 - 序列化配置:若API的JSON命名规则与C#不一致(如下划线转驼峰),可自定义序列化选项:
var serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, // 忽略字段大小写匹配 PropertyNamingPolicy = JsonNamingPolicy.CamelCase // 自动转换驼峰命名 }; return await response.Content.ReadFromJsonAsync<ApiResponse>(serializerOptions);
- 异常处理:除了
EnsureSuccessStatusCode(),也可手动判断response.StatusCode,针对4xx/5xx状态码做自定义错误处理。
内容的提问来源于stack exchange,提问作者Furkan Talan
相关产品推荐
相关产品推荐

