【问题标题】:RestSharp portable add json body from userinput fieldRestSharp便携式从用户输入字段添加json正文
【发布时间】:2017-10-16 18:36:46
【问题描述】:

在我的 UWP 应用程序中,用户可以在文本字段中输入 json 正文,并通过 restsharp 便携式将其设置为 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);

但这不是干净的方式

【问题讨论】:

  • 完整的请求定义是什么?你也加了request.RequestFormat = DataFormat.Json;吗?
  • RestRequest 类没有 RequestFormat 成员
  • 你能把整个代码都过去吗?
  • var restClient = new RestClient(baseUri); var request = new RestRequest(path, Method.POST); request.AddParameter("application/json; charset=utf-8", requestBody, ParameterType.RequestBody); ar response = await restClient.Execute(request);
  • 您是否尝试过 Microsoft.Net.HttpClient,因为 ResharpPortable 不再维护,所以看起来更直接。

标签: c# json rest uwp restsharp


【解决方案1】:

对我有用的代码示例:

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

【讨论】:

  • 在 restsharp.portable 库中,RestRequest 类没有 RequestFormat 成员
  • 啊哈,不知道您使用的是 .NET Core/Portable(虽然它在问题的标题中......)。也许可以尝试对正文进行 UTF-8 编码:var someBody = Encoding.UTF8.GetBytes(requestBody); 并在 AddParameter 方法中使用它。
  • 有效:var someBody = Encoding.UTF8.GetBytes(requestBody); request.AddParameter("application/json; charset=utf-8", someBody, ParameterType.RequestBody);谢谢
猜你喜欢
  • 2018-03-19
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多