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

JSON请求体持续返回Bad Request:变量取值报错硬编码正常

解决C#字符串插值拼接JSON请求体返回Bad Request的问题

问题场景

通过字符串插值拼接JSON请求体,使用projectRecordsJson的属性值填充时,请求返回Bad Request错误;但将值硬编码到JSON中时,请求可正常执行。相关代码如下:

var url = "<SOMEURL>";
var apiKey = "<SOMEKEY>";

var client = new HttpClient();
var uri = new Uri(url);

/** I believed something wrong here, if I changed the value into hard-code value it works **/
var json = $@"{{
                 ""Uin"": ""{projectRecordsJson.Uin}"" ,
                 ""ProjectId"": ""{projectRecordsJson.ProjectId}"" ,
                 ""DeleteFlag"": ""{projectRecordsJson.DeleteFlag}"" ,
                 ""Type"": ""{projectRecordsJson.Type}"" ,
                 ""StopDate"": ""{projectRecordsJson.StopDate}"" ,
                 ""TerminationFlag"": ""{projectRecordsJson.TerminationFlag}"" ,
                 ""A05Flag"": ""{projectRecordsJson.A05Flag}""
             }}";
 
var content = new StringContent(json, Encoding.UTF8, "application/json");

// Add API key as a request header
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);

var response = await client.PostAsync(uri, content);

if (response.IsSuccessStatusCode)
{
    var responseContent = await response.Content.ReadAsStringAsync();
    Console.WriteLine("Response:");
    Console.WriteLine(responseContent);
}
else
{
    Console.WriteLine("Error:");
    Console.WriteLine($"{response.StatusCode} - {response.ReasonPhrase}");
}

问题原因

手动通过字符串插值拼接JSON容易出现以下问题:

  • JSON格式无效:如果变量值包含双引号、反斜杠、换行符等特殊字符,未转义会直接破坏JSON结构
  • 类型不匹配:比如DeleteFlag如果是布尔值,硬编码时是true(无引号),但插值会变成"true"(字符串类型),不符合API对参数类型的要求
  • 空值/格式问题:变量为null时,插值后会生成""null""这类无效值,或者拼接时的空格、逗号位置错误导致JSON语法错误

解决方案

推荐方案:使用JSON序列化库(最稳妥)

直接用C#内置的System.Text.Json或者第三方库Newtonsoft.Json将对象序列化为JSON,完全避免手动拼接的问题。

使用System.Text.Json的示例:

var url = "<SOMEURL>";
var apiKey = "<SOMEKEY>";

var client = new HttpClient();
var uri = new Uri(url);

// 构建请求体对象
var requestBody = new 
{
    Uin = projectRecordsJson.Uin,
    ProjectId = projectRecordsJson.ProjectId,
    DeleteFlag = projectRecordsJson.DeleteFlag,
    Type = projectRecordsJson.Type,
    StopDate = projectRecordsJson.StopDate,
    TerminationFlag = projectRecordsJson.TerminationFlag,
    A05Flag = projectRecordsJson.A05Flag
};

// 序列化为JSON
string json = JsonSerializer.Serialize(requestBody);

var content = new StringContent(json, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);

var response = await client.PostAsync(uri, content);

if (response.IsSuccessStatusCode)
{
    var responseContent = await response.Content.ReadAsStringAsync();
    Console.WriteLine("Response:");
    Console.WriteLine(responseContent);
}
else
{
    Console.WriteLine("Error:");
    Console.WriteLine($"{response.StatusCode} - {response.ReasonPhrase}");
}

使用Newtonsoft.Json的示例:

如果使用Newtonsoft.Json,只需替换序列化部分:

string json = JsonConvert.SerializeObject(requestBody);

临时方案:排查并修正字符串插值问题

如果必须用字符串插值,需要逐个检查变量:

  • 检查变量值是否包含特殊字符,用JsonEncodedText.Encode处理字符串值实现转义
  • 确认参数类型:如果是布尔值、数字类型,去掉JSON中的引号,比如"DeleteFlag": {projectRecordsJson.DeleteFlag}
  • 检查变量是否为null,提前处理空值(比如替换为空字符串或符合API要求的默认值)
  • 拼接后输出json变量,对比硬编码的JSON,检查格式差异

内容的提问来源于stack exchange,提问作者Chris Angeles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:59:51