【问题标题】:RestSharp removing dot from bodyRestSharp 从身体上去除点
【发布时间】:2015-07-09 04:06:53
【问题描述】:

我正在使用 restsharp 向我的端点执行 POST 请求。

当我添加正文时,我会这样做:

request.AddParameter("text/json", message, ParameterType.RequestBody);

字符串消息是这样完成的:VALUE1.VALUE2 真的很简单。

但我的端点只收到 VALUE1

端点签名是:

[HttpPost]
public HttpResponseMessage DoJob([FromBody] string id)

你知道为什么吗?我必须以某种方式对我发送的消息进行编码吗?

出于测试目的对邮递员做同样的事情我没有遇到这种行为。

谢谢!

【问题讨论】:

  • 如何在端点中获取参数?或者您可以添加端点定义和网址吗?
  • @Chase:我更新了问题

标签: c# .net asp.net-web-api2 restsharp


【解决方案1】:

这是我的 RestSharp 版本 105.1.0.0 的工作示例:

var message = "VALUE1.VALUE2"
var client = new RestClient("http://localhost:64648"); //replace with your domain name
var request = new RestRequest("/Home/DoJob", Method.POST); //replace 'Home' with your controller name
request.RequestFormat = DataFormat.Json;
request.AddBody(new { id = message });
client.Execute(request);

还有我的端点定义

[HttpPost]
public HttpResponseMessage DoJob([System.Web.Http.FromBody] string id) {
  //some code
}

一切都按预期进行。

顺便说一句,如果你想要发布数组,你只需要改变两个地方:

request.AddBody(new { ids = message.Split('.') });

及定义

[HttpPost]
public HttpResponseMessage DoJob([System.Web.Http.FromBody] string[] ids) {
  //some code
}

【讨论】:

    【解决方案2】:

    我通过另一种方式解决了这个问题。

    代替:

    request.AddParameter("text/json", message, ParameterType.RequestBody);
    

    我说:

    request.RequestFormat = DataFormat.Json;
    request.AddBody(message);
    

    现在无论消息中包含什么字符,消息内容(只要是 json)都会正确传递到我的端点

    【讨论】:

    • 为什么我第一次发的时候你不接受?)
    • @Chase:因为我后来明白这是正确答案:)
    • 为什么你又改变了你的看法,这很有趣?)顺便说一句,你在这篇文章中的当前解决方案不起作用,因为你对 API 的定义正在等待 id 参数并且你没有定义它,所以你的 id 在行动中总是为空的。但是您将其设置为答案。你是个有趣的家伙)
    • @Chase:实际上正在工作。我不明白你对 id 参数的评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2012-05-25
    相关资源
    最近更新 更多