【问题标题】:using http party to send json to web api使用 http 方将 json 发送到 web api
【发布时间】:2014-04-08 03:47:51
【问题描述】:

我正在使用 http 派对 gem 尝试将一些 json 发送到我在 Visual Studio 中运行的 Web api。

我的 Post API 的 C# 实现如下:

 public string GetInfo([FromBody]MyClass[] postedValues)
 {
   //do stuff

如果我将 fiddler 配置为点击该方法并在 fiddler 中将请求标头设置为:

Content-Type: application/json; charset=utf-8

然后是请求正文:

[{"Id" : "1", "A" : "1", "B" : "1", "c" : "1"}, {"Id" : "2", "A" : "2", "B" : "2", "C" : "2"}]

当我点击执行时,postedValues 会自动将 json 中的值映射到数组中 - 因此对于上述情况,数组中将有 2 个元素 - MyClass postedValues[0] 中的 Id 将是 1postedValues[1] 中的 Id 将是 2 并且所有其他属性都相同。

我想从 Ruby on Rails 访问 WebAPi,所以我使用 http 方并构建请求如下(注意完整的 http:// 从 URL 中取出):

post('localhost/api/MyController/GetInfo', :body => [{:Id => '1',
                                                     :A => '1',
                                                     :B => '1',
                                                     :C => '1'}].to_json,
                         :headers => {'Content-Type' => 'application/json'})

但是现在如果我在我的 C# 方法中放置一个断点 postedValues 是空的。如果我将 C# 方法更改为:

public string GetInfo([FromBody]dynamic postedValues)
{
       //do stuff

并运行 Ruby 代码,我确实看到传递的值,但如果这些值是自动映射的,就像我从 Fiddler 中击中它时那样自动映射,我会更喜欢 - 我在 http 派对上做错了什么吗?

【问题讨论】:

  • 您能看出原始请求(手动与 ruby​​)之间的区别吗?
  • 嗨@UriAgassi - 通过 Fiddler 请求,我可以看到正在发送的 JSON(来自 Fiddler) - 通过 Ruby 请求 - 它在 127.0.0.1:3000 上运行 - 我在 Fiddler 中看不到任何东西被发送当我到达断点时..
  • 我不确定您是否可以使用 fiddler 查看原始请求 - 试试 stackoverflow.com/a/7292900/1120015
  • @KOL:您可以在控制器内部使用Request.Content 来访问原始请求。在此处发布差异:)
  • @David - 感谢您的提示 - 我会尝试并使用结果编辑我的问题

标签: c# ruby-on-rails ruby json asp.net-web-api


【解决方案1】:

我最终将请求正文提取到一个类级别变量中,它可以按预期映射值 - 希望这对其他人有用。

  @request_body = [{:Id => '1',
                    :A => '1',
                    :B => '1',
                    :C=> '1'}]

    post('localhost:50544/api/MyController/GetInfo', :body => @request_body.to_json,
                                     :headers => {'Content-Type' => 'application/json'})

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 2012-12-01
    • 2017-04-07
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    相关资源
    最近更新 更多