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

使用RestClient添加JSON请求体遇MESSAGE_NOT_READABLE错误求助

正确在RestClient中添加JSON请求体的方法

问题根源

你之前的尝试存在两个问题:

  1. 直接用AddBody传递字符串时,RestClient默认不会将请求的Content-Type设为application/json,导致服务端无法按JSON格式解析请求体。
  2. 第二次尝试的JSON存在语法错误(id值后多了一个逗号),属于无效JSON结构。

正确方案

方案一:使用强类型对象(推荐,避免手动拼接JSON出错)

先定义与JSON结构匹配的实体类:

using Newtonsoft.Json; // 需要引用Newtonsoft.Json包,或使用System.Text.Json

public class DeviceConfigurationGeneral
{
    [JsonProperty("id")]
    public string Id { get; set; }
}

public class RequestBody
{
    [JsonProperty("device_configuration_general")]
    public DeviceConfigurationGeneral DeviceConfigurationGeneral { get; set; }
}

然后构建对象并添加到请求:

var client = new RestClient(signUrl);
var request = new RestRequest(Method.Put);

var requestBody = new RequestBody
{
    DeviceConfigurationGeneral = new DeviceConfigurationGeneral
    {
        Id = "fffc16e2-2cf3-40f6-92df-a5b65e617b1c"
    }
};

request.AddJsonBody(requestBody); // 自动设置Content-Type为application/json并序列化对象

RestResponse response = await client.ExecuteAsync(request);

方案二:手动构造正确JSON字符串并指定Content-Type

确保JSON语法完全正确(无多余逗号),然后用AddStringBody方法明确指定内容类型:

var client = new RestClient(signUrl);
var request = new RestRequest(Method.Put);

var body = "{\"device_configuration_general\": {\"id\": \"fffc16e2-2cf3-40f6-92df-a5b65e617b1c\"}}";
request.AddStringBody(body, ContentType.Json);

RestResponse response = await client.ExecuteAsync(request);

额外提示

  • 不要在RestRequest构造函数中重复传递signUrl,RestClient已经持有该地址。
  • 手动拼接JSON时,可使用JSON校验工具验证语法正确性,避免低级错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:45:10