RestSharp 便携式从用户输入字段添加 json 正文

RestSharp portable add json body from userinput field

在我的 UWP 应用程序中,用户可以在文本字段中输入 json 正文,并通过 restsharp portable 将其设置为 POST Rest-Request 中的正文。

所以用户将其输入文本框(值绑定到 requestBody):

{  "string": "Hello World"}

然后我将字符串添加到请求中:

request.AddParameter("application/json; charset=utf-8", requestBody, ParameterType.RequestBody);

正文已添加,但不正确。 服务器不解析传入的 json 正文。

我不知道出了什么问题,但我认为有些字符编码不正确。

有没有人设法用这种方式添加一个json正文?


此解决方案有效:

var b = JsonConvert.DeserializeObject<Object>(requestBody);
request.AddJsonBody(b);

但这不是干净的方法

对我有用的代码示例:

var client = new RestClient("http://localhost");
var request = new RestRequest("pathtoservice", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("application/json", "{ \"Some\": \"Data\" }", ParameterType.RequestBody);
var result = client.Execute(request);

为完整起见,当使用 RestSharp Portable 时,以上内容为:

var client = new RestClient("http://localhost");
var request = new RestRequest("pathtoservice", Method.POST);
var requestBody = Encoding.UTF8.GetBytes("{ \"Some\": \"Data\" }");
request.AddParameter("application/json; charset=utf-8", requestBody, ParameterType.RequestBody);
var result = client.Execute(request);