You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中为Postman生成代码的JSON请求体设置变量数据

解决方案

以下是两种可直接落地的实现方式:

推荐方案:使用JSON序列化生成请求体(无转义错误风险)

手动拼接JSON字符串极容易出现转义错误,优先使用序列化库生成请求体:

  • 首先通过NuGet安装 Newtonsoft.Json 包(也可使用.NET内置的System.Text.Json)
  • 完整修改后代码:
// 定义动态Age变量
int variable_age = 72;

var client = new RestClient("https://azuretitanicapp.azurewebsites.net/predict");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic PEJhc2ljIEF1dGggVXNlcm5hbWU+OjxCYXNpYyBBdXRoIFBhc3N3b3JkPg==");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "ARRAffinity=a6e48b9e9d2653435be7b61998d8624b44115214104213d6c8b8c526cc56dc70; ARRAffinitySameSite=a6e48b9e9d2653435be7b61998d8624b44115214104213d6c8b8c526cc56dc70");

// 构造匿名对象自动序列化,无需手动处理转义
var bodyObj = new 
{
    Pclass = "2",
    Age = variable_age.ToString() // 原接口要求Age传字符串类型,若要求数字则直接写variable_age即可
};
string body = Newtonsoft.Json.JsonConvert.SerializeObject(bodyObj);

request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

轻量方案:使用字符串插值快速修改(仅适合简单场景)

如果不想额外引入序列化库,可以用C#的插值逐字字符串实现变量注入,注意大括号需要双写转义:

// 定义动态Age变量
int variable_age = 72;

var client = new RestClient("https://azuretitanicapp.azurewebsites.net/predict");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic PEJhc2ljIEF1dGggVXNlcm5hbWU+OjxCYXNpYyBBdXRoIFBhc3N3b3JkPg==");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "ARRAffinity=a6e48b9e9d2653435be7b61998d8624b44115214104213d6c8b8c526cc56dc70; ARRAffinitySameSite=a6e48b9e9d2653435be7b61998d8624b44115214104213d6c8b8c526cc56dc70");

// 插值逐字字符串实现变量注入
var body = $@"{{
    ""Pclass"": ""2"",
    ""Age"": ""{variable_age}""
}}";

request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

注意事项

如果后续接口调整要求Age字段为数字类型而非字符串,只需要删除Age值两侧的双引号即可,对应轻量方案的写法改为:
""Age"": {variable_age}

内容的提问来源于stack exchange,提问作者Mukesh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:15:08