2015-11-03 80 views
1

因此,在過去的2天中,我一直試圖在github存儲庫中添加新問題。這似乎相當簡單。 documentation說只是添加一些JSON,然後發送它的方式。嘗試添加JSON主體以請求使用RestSharp時的錯誤請求

我第一次做的一個問題:

 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

+1

如果你發送的是JSON,那麼內容類型不應該是'application/json'而不是'application/x-www-form-urlencoded'嗎?另外,你確定你的內容長度是正確的嗎?即使考慮了字符串中的轉義字符,您發佈的JSON字符串也超過了100個字符。 –

+0

感謝您的建議。沒有運氣,但:( – newnottakenname

+1

'content-length'仍然@ 1200.我認爲你可以完全離開那個。試着先用postman這樣的東西來做這個帖子。可能會啓發一些東西 – Rik

回答

1

休息尖銳的建議有一個內置的方法,用於將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; 
} 

可能會刪除某些不確定性與你的電話