简体   繁体   English

使用http party将json发送到Web API

[英]using http party to send json to web api

I am using http party gem to try and send some json to a web api I have running in Visual Studio. 我正在使用http party gem尝试将一些json发送到我在Visual Studio中运行的Web API。

The C# implementation of my Post API is as below: 我的Post API的C#实现如下:

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

If I configure fiddler to hit the method and within fiddler set the request header to be: 如果我将提琴手配置为使用该方法,并且在提琴手中将请求标头设置为:

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

and then the request body to be: 然后请求正文为:

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

when I hit execute the postedValues automatically maps the values from the json into the array - so for the above there will be 2 elements in the array - the Id in MyClass postedValues[0] will be 1 and the Id in postedValues[1] will be 2 and the same for all the other properties. 当我打执行postedValues自动从JSON的值映射到阵列-因此,对于上面会有阵列中的2种元素- IdMyClass postedValues[0]将是1IdpostedValues[1]将为2 ,其他所有属性均相同。

I want to hit the WebAPi from Ruby on Rails so I am using http party and building the request as below(note full http:// taken out of URL): 我想从Ruby on Rails中访问WebAPi,所以我正在使用http party并按如下方式构建请求(注意,完整的http://从URL中删除):

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

However now if I put a breakpoint in my C# method postedValues is null. 但是现在,如果我在C#方法中放置一个断点,则postedValues为null。 If I change the C# method to: 如果我将C#方法更改为:

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

and run the Ruby code I do see values passed but would much prefer if the values were mapped automatically as they are when I hit it from Fiddler - is there something I am doing incorrect with http party? 并运行Ruby代码,我确实看到了传递的值,但是如果这些值是自动映射的,则更喜欢从Fiddler击中值时的样子-我在使用HTTP派对时是否做错了什么?

I ended up pulling the request body out into a class level variable and it worked mapping the values as expected - hopefully this is useful to someone else. 最后,我将请求主体拉到了类级别的变量中,并且它按预期方式映射了值-希望这对其他人很有用。

  @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'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM