0

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?

1
  • It's param1 not paramater1, and it should be {"param1": "value1"} not value1. Commented Feb 7, 2014 at 13:50

2 Answers 2

2

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 - e.g. 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...

Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.