PutAsJsonAsync无法正确设置请求体,如何生成Postman式Raw JSON请求体?
代码PUT请求匹配Postman Raw JSON格式问题解决
问题描述
调用第三方API时,Postman中用PUT请求能成功将status和ivrstatus字段设为"cancelled",但C#代码里通过PutAsJsonAsync传递IdcInputParameters对象时,API返回500错误,提示无效输入参数,怀疑请求体格式与Postman不一致,试过多种方案未解决,需实现和Postman一致的Raw JSON请求体。
代码示例
var idcInput = new IdcInputParameters( status: "cancelled", ivrstatus: "cancelled" ); // 向RFS传递更新参数 using HttpResponseMessage httpResponse = await RfsApiClient.ApiClient.PutAsJsonAsync(uri, idcInput); var res = await httpResponse.Content.ReadAsStringAsync(); if (httpResponse.IsSuccessStatusCode) { Idc? idc = JsonConvert.DeserializeObject<Idc>(res); return idc; }
当前JsonSerializer输出:
{"status":"cancelled","ivrstatus":"cancelled"}
解决方案
1. 直接构造JSON字符串发送
绕过自动序列化,手动构造和Postman完全一致的JSON内容,用StringContent指定正确的Content-Type:
// 构造与Postman一致的Raw JSON字符串 string jsonBody = "{\"status\":\"cancelled\",\"ivrstatus\":\"cancelled\"}"; // 创建请求内容,设置编码和Content-Type var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); using HttpResponseMessage httpResponse = await RfsApiClient.ApiClient.PutAsync(uri, content); var res = await httpResponse.Content.ReadAsStringAsync(); if (httpResponse.IsSuccessStatusCode) { Idc? idc = JsonConvert.DeserializeObject<Idc>(res); return idc; }
2. 统一序列化配置
PutAsJsonAsync默认用System.Text.Json序列化,而代码中用Newtonsoft.Json反序列化,两者行为可能存在差异,需统一序列化规则:
方案A:配置System.Text.Json匹配API要求
var jsonOptions = new JsonSerializerOptions { // 若API要求驼峰命名则开启,否则可移除 PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 关闭缩进,和Postman Raw JSON格式一致 WriteIndented = false }; using HttpResponseMessage httpResponse = await RfsApiClient.ApiClient.PutAsJsonAsync(uri, idcInput, jsonOptions);
方案B:用Newtonsoft.Json序列化后发送
// 用Newtonsoft.Json序列化对象,确保输出格式和Postman一致 string jsonBody = JsonConvert.SerializeObject(idcInput, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.None // 无缩进 }); var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); using HttpResponseMessage httpResponse = await RfsApiClient.ApiClient.PutAsync(uri, content);
3. 对齐请求头
检查Postman中的请求头(比如Content-Type、Authorization、Accept等),确保代码中的请求头完全一致,可通过以下方式添加缺失的头:
// 示例:添加Authorization头 RfsApiClient.ApiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your-token");
4. 抓包对比请求体
用Fiddler或Charles抓取代码发送的请求,和Postman的请求体做对比,排查是否存在额外字段、转义错误或格式差异。
内容的提问来源于stack exchange,提问作者Kevin Z
相关产品推荐
相关产品推荐

