Bad Request when trying to add JSON body to request with RestSharp

跟風遠走 提交于 2019-12-11 13:52:11

问题


So for the last 2 days I have been trying to add a new issue on a github repository. This seems fairly simple. The documentation says to just add some JSON and then send it on its way.

I first make an issue:

        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; }
        }

and then create a call using 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>());

and then makes the call. However it then never fails to return a 400: Bad Request.

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

I tried different bodies, post parameters and the example. None of them want to work. Does anyone have any idea what I am doing wrong?

EDIT: Changed content-type and length on the suggestion of Brian


回答1:


Rest sharp has a built in method for adding JSON data to a request:

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;
}

Might remove some of the uncertainty with your call



来源:https://stackoverflow.com/questions/33508073/bad-request-when-trying-to-add-json-body-to-request-with-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!