尝试将 JSON 正文添加到 RestSharp 请求时出现错误请求 [英] Bad Request when trying to add JSON body to request with RestSharp
问题描述
所以在过去的 2 天里,我一直在尝试在 github 存储库中添加一个新问题.这看起来相当简单.文档 说只需添加一些 JSON 然后将其发送它的方式.
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.
我首先提出一个问题:
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 创建调用
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>());
然后拨打电话.然而,它永远不会失败返回 400: Bad Request.
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?
根据 布莱恩
推荐答案
RestSharp 有一个内置的方法可以将 JSON 数据添加到请求中:
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
这篇关于尝试将 JSON 正文添加到 RestSharp 请求时出现错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!