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

使用RestSharp发送JSON格式POST请求时遭遇DOCTYPE错误求助

排查RestSharp POST请求错误的问题

我看了你这段用RestSharp发送POST请求的代码,发现几个很可能导致错误的问题,咱们一步步来修正:

主要问题分析

  • 冗余的JSON序列化操作:你现在的代码里多次嵌套调用JsonConvert的序列化/反序列化方法,完全是画蛇添足。手动拼接JSON字符串再反序列化,最后又序列化,不仅低效,还容易引入格式错误。
  • 错误使用AddJsonBody:RestSharp的AddJsonBody方法设计用来接收对象,它会自动帮你把对象序列化为JSON字符串。但你现在传入的是已经序列化好的JSON字符串,这会导致RestSharp把这个字符串再次转义序列化,最终发送的请求体格式完全不符合后端预期。

修正后的代码

private readonly string contentType = "application/json";
try
{
    var restClient = new RestClient(new Uri(InvoiceExpressURLS.URL_createClient));
    
    // 直接构造包含client属性的对象,无需手动拼接JSON
    var requestBody = new { client = newClient };
    
    var request = new RestRequest(Method.POST);
    request.RequestFormat = DataFormat.Json;
    request.AddHeader("Content-Type", contentType);
    // 直接传入对象,RestSharp会自动序列化
    request.AddJsonBody(requestBody);
    
    var restResponse = await restClient.ExecuteTaskAsync<object>(request);
    if (restResponse.IsSuccessful)
    {
        response.responseObject = restResponse.Data;
        response.responseMessage = string.Format("The client \"{0}\" was successfully created.", newClient.name);
    }
    else
    {
        response.responseStatus = restResponse.StatusCode;
        response.responseMessage = restResponse.ErrorMessage;
    }
}
catch (Exception e)
{
    response.responseStatus = HttpStatusCode.InternalServerError;
    response.responseMessage = e.Message;
    response.responseObject = e;
}

额外调试建议

  • 开启RestSharp的请求日志,查看实际发送的请求体和请求头,确认格式是否符合API要求
  • 验证InvoiceExpressURLS.URL_createClient是否为有效的API端点地址
  • 检查newClient的属性结构、数据类型是否完全匹配后端API的接收规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:00:28