简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM