尝试使用RestSharp添加JSON主体以请求时出现错误请求

时间:2015-11-03 20:05:04

标签: c# .net json restsharp

因此,在过去的两天里,我一直在尝试在github存储库中添加新问题。这看起来相当简单。 enter image description here说只是添加一些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"
        }

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

编辑:根据documentation

的建议更改了内容类型和长度

1 个答案:

答案 0 :(得分: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;
}

可以通过电话消除一些不确定因素

相关问题