如何在C#的API Post方法中传递JSON请求体
在C#的API Post方法中传递JSON请求体的实现方式
下面是两种常用的实现方案,针对你提供的JSON请求体,分别给出代码示例:
方案一:使用强类型模型(推荐,利于维护和类型检查)
首先根据你的JSON结构定义对应的C#类:
public class PaymentRequest { public string intent { get; set; } public List<PurchaseUnit> purchase_units { get; set; } public ApplicationContext application_context { get; set; } } public class PurchaseUnit { public Amount amount { get; set; } } public class Amount { public string currency_code { get; set; } public string value { get; set; } } public class ApplicationContext { public string return_url { get; set; } public string cancel_url { get; set; } }
然后使用HttpClient发送Post请求(.NET Core/.NET 5+推荐使用):
using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using System.Collections.Generic; class PaymentSender { static async Task Main(string[] args) { // 构造请求数据 var requestData = new PaymentRequest { intent = "CAPTURE", purchase_units = new List<PurchaseUnit> { new PurchaseUnit { amount = new Amount { currency_code = "USD", value = "10" } } }, application_context = new ApplicationContext { return_url = "https://example.com/return", cancel_url = "https://example.com/cancel" } }; // 将对象序列化为JSON字符串 string json = JsonSerializer.Serialize(requestData); var content = new StringContent(json, Encoding.UTF8, "application/json"); // 注意:实际项目中HttpClient应复用单例,避免频繁创建 using var client = new HttpClient(); try { HttpResponseMessage response = await client.PostAsync("你的API接口地址", content); response.EnsureSuccessStatusCode(); // 若请求失败会抛出异常 string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("API响应:" + responseBody); } catch (HttpRequestException ex) { Console.WriteLine("请求失败:" + ex.Message); } } }
方案二:直接使用匿名对象(快速实现,无需定义模型)
如果不想定义实体类,可以直接构造匿名对象并序列化,这里以Newtonsoft.Json为例(需先安装Newtonsoft.Json NuGet包):
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; class PaymentSender { static async Task Main(string[] args) { var requestData = new { intent = "CAPTURE", purchase_units = new[] { new { amount = new { currency_code = "USD", value = "10" } } }, application_context = new { return_url = "https://example.com/return", cancel_url = "https://example.com/cancel" } }; string json = JsonConvert.SerializeObject(requestData); var content = new StringContent(json, Encoding.UTF8, "application/json"); using var client = new HttpClient(); try { HttpResponseMessage response = await client.PostAsync("你的API接口地址", content); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("API响应:" + responseBody); } catch (HttpRequestException ex) { Console.WriteLine("请求失败:" + ex.Message); } } }
关键注意事项
- 务必设置请求内容的
Content-Type为application/json,否则API可能无法正确解析请求体 - 生产环境中,
HttpClient建议复用单例实例,避免频繁创建导致的资源泄漏 - 可根据API要求调整序列化配置(比如大小写、忽略空值等)
内容的提问来源于stack exchange,提问作者Nikhil Jose
相关产品推荐
相关产品推荐

