簡體   English   中英

嘗試添加JSON正文以使用RestSharp請求時出現錯誤請求

[英]Bad Request when trying to add JSON body to request with RestSharp

所以在過去的兩天里,我一直在嘗試在github存儲庫上添加一個新的問題。 這似乎很簡單。 文檔說,只需添加一些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:Bad Request。

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

我嘗試了不同的正文,發布參數和示例。 他們都不想工作。 有人知道我在做什么錯嗎?

編輯:在布萊恩的建議下更改了內容類型和長度

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

可能會消除您通話中的一些不確定性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM