我正试图称呼这个
[Route("CreateHL7TestFile")]
[HttpPost]
public IActionResult CreateHL7TestFile([FromBody] JObject data)
{
// Code here
}
使用cUrl从php函数获取。当我尝试调用API而不传递任何数据时,它工作正常。当我尝试添加'$ data'时,我无法使用该API。当我用Postman的数据调用API时,它也可以正常工作。所以我假设我的错误是在PHP方面?
我的php函数如下所示。
public function CallAPI($method, $url, $data = false)
{
$data = array("value1" => "some value");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('test1' => 'value1', 'test2' => 'value2')));
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
}
http://localhost:50999/api/ParticipantAPI/CreateHL7TestFile
任何帮助将不胜感激。 谢谢, 亚当
答案 0 :(得分:1)
尝试这样的事情:
public function CallAPI($method, $url, $data = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('test1' => 'value1', 'test2' => 'value2')));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
}
如果要发送json,那么我认为您必须设置标头,例如:
public function CallAPI($method, $url, $data = false)
{
$dat = array("TEST1","TEST2");
$data = json_encode($dat);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
}
答案 1 :(得分:1)
在asp.net核心服务器上使用适当的模型来绑定传入数据
public class MyData {
public string value1 { get; set;}
}
并相应地更新操作
[Route("CreateHL7TestFile")]
[HttpPost]
public IActionResult CreateHL7TestFile([FromBody] MyData data) {
// Code here
}
参考以下文章POSTing JSON Data With PHP cURL
在PHP方面尝试以下操作
$data = array("value1" => "some value");
$data_string = json_encode($data);
$ch = curl_init($url);
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);
print_r($result);
curl_close($ch);
对于您的实际请求,请相应地重构预期的数据模型。