简体   繁体   中英

How to pass POST parameters from PHP to ASP Web Api?

My server is a Asp Net Web Api application. It works fine but now I try to call some services from PHP.

The .Net code is:

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

In PHP side, I use:

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

Using the Debug, the .Net service is effectively called from PHP, id is assigned to 5, but the POST "paramater1" parameter is always null, not "value1".

What am I doing wrong?

Some items to check (am not a PHP dev);

  • using [FromBody] - note that the POST body format should be =foo (not the key value pair you'd expect - eg 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)."

REF:

Hth...

I'm not familiar with PHP but I assume the request body will be like this for the code you have shown.

{"param1" : "value1"}

If this is correct, you need to have your action method and a DTO class like this for binding to work.

public void Post(int id, MyType myParam) { }

public class MyType
{
    public string Param1 { get; set; }
}

Now, with this you can see that Param1 property of the myParam parameter is set to value1 .

By default, body gets bound to a complex type like MyType class here. If you want to bind to a simple type, you cannot have a key-value pair. Since the body gets bound in entirety to one parameter, you will somehow need to specify your request in PHP so that only the value gets sent, without the key, like this.

"value1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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