【问题标题】:How to pass POST parameters from PHP to ASP Web Api?如何将 POST 参数从 PHP 传递到 ASP Web Api?
【发布时间】:2014-03-04 23:01:33
【问题描述】:

我的服务器是一个 Asp Net Web Api 应用程序。它工作正常,但现在我尝试从 PHP 调用一些服务。

.Net 代码是:

public void Post(int id, [FromBody] string param1)

在 PHP 方面,我使用:

$data = array("param1" => "value1");
$data_string = json_encode($data);
$ch = curl_init('http://localhost:53816/api/enterpriseapi/5');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
 'Content-Type: application/json',
 'Content-Length: ' . strlen($data_string))
); 
$result = curl_exec($ch);

使用 Debug,从 PHP 中有效调用 .Net 服务,id 赋值为 5,但 POST 的“paramater1”参数始终为空,而不是“value1”。

我做错了什么?

【问题讨论】:

  • param1 不是paramater1,应该是{"param1": "value1"} 而不是value1

标签: php asp.net web-services asp.net-web-api


【解决方案1】:

需要检查的一些项目(我不是 PHP 开发人员);

  • 使用[FromBody] - 注意POST 正文格式应该 =foo(不是您期望的键值对 - 例如bar=foo

  • "When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object)."

参考:

第...

【讨论】:

    【解决方案2】:

    我不熟悉 PHP,但我认为对于您显示的代码,请求正文将是这样的。

    {"param1" : "value1"}
    

    如果这是正确的,你需要有你的动作方法和一个像这样的 DTO 类才能绑定工作。

    public void Post(int id, MyType myParam) { }
    
    public class MyType
    {
        public string Param1 { get; set; }
    }
    

    现在,您可以看到myParam 参数的Param1 属性设置为value1

    默认情况下,body 被绑定到一个复杂类型,比如这里的MyType 类。如果要绑定到简单类型,则不能有键值对。由于正文完全绑定到一个参数,因此您需要以某种方式在 PHP 中指定您的请求,以便只发送值,而不发送密钥,就像这样。

    "value1"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-05
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2016-09-27
      • 1970-01-01
      相关资源
      最近更新 更多