【问题标题】:Bad Request when trying to add JSON body to request with RestSharp尝试使用 RestSharp 将 JSON 正文添加到请求时出现错误请求
【发布时间】:2015-11-10 16:46:17
【问题描述】:

所以在过去的两天里,我一直在尝试在 github 存储库上添加一个新问题。这看起来相当简单。 documentation 表示只需添加一些 JSON,然后将其发送出去。

我先提出一个问题:

        public class RequestIssue
        {
            public string title { get; set; }
            public string body { get; set; }
            public string assignee { get; set; }
            public int milestone { get; set; }
            public List<string> labels { get; set; }
        }

然后使用 RestSharp 创建调用

        string text = JsonConvert.SerializeObject(issue);
        string text2 =
            "{  \"title\": \"Found a bug\",  \"body\": \"I'm having a problem with this.\",  \"assignee\": \"octocat\",  \"milestone\": 1,  \"labels\": [\"Label1\", \"Label2\"] }";
        parameters.Add(new Param("body", text2));

        UpdateParameterIfExists(new Param("content-type", "application/json"));
        UpdateParameterIfExists(new Param("content-length", "1200"));

        IRestRequest req = new RestRequest(repo.issues_url, Method.POST);
        //req.AddJsonBody(text);
        //req.AddObject(issue);
        req.AddBody(text2, null);

        req.AddParameter("application/json", text2, ParameterType.RequestBody);
        req.AddParameter("text/json", text2, ParameterType.RequestBody);
        req.AddParameter("json", text2, ParameterType.RequestBody);
        req.AddParameter("body", text2, ParameterType.RequestBody);
        req.AddParameter("data", text2, ParameterType.RequestBody);

        await addParametersAndMakeCall(req, new List<Param>());

然后拨打电话。但是,它永远不会返回 400:错误请求。

        {
              "message":"Problems parsing JSON",
              "documentation_url":"https://developer.github.com/v3/issues/#create-an-issue"
        }

我尝试了不同的主体、发布参数和示例。他们都不想工作。有谁知道我做错了什么?

编辑:根据Brian 的建议更改了内容类型和长度

【问题讨论】:

  • 如果你发送 JSON,内容类型不应该是 application/json 而不是 application/x-www-form-urlencoded 吗?另外,您确定您的内容长度正确吗?即使考虑到字符串中的转义,您发布的 JSON 字符串也有超过 100 个字符。
  • 感谢您的建议。不过运气不好:(
  • content-length 仍然是@ 1200。我认为您可以完全忽略那个。尝试先用邮递员之类的东西来发帖。可能会启发一些东西
  • 为什么不将content-length 设置为实际长度(即text2.Length)?这将消除它作为问题的根源。
  • 成功了,谢谢!

标签: c# .net json restsharp


【解决方案1】:

Rest sharp 有一个用于将 JSON 数据添加到请求的内置方法:

public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
{
    var request = new RestRequest(apiEndPoint, Method.POST);

    request.AddJsonBody(objectToUpdate); // HERE

    var response = _restClient.Execute<T>(request);
    return response;
}

可能会消除您通话中的一些不确定性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2020-12-07
    • 2019-05-29
    • 2019-10-10
    • 1970-01-01
    • 2019-09-05
    相关资源
    最近更新 更多