将文件内容从php curl(使用post)发送到c#webapi
我必须将一个文件对象从php传输到c#webapi。 不知何故,在c#中,文件内容是空的。 这是去掉其他东西后的部分PHP代码将文件内容从php curl(使用post)发送到c#webapi,c#,php,asp.net,curl,asp.net-web-api,C#,Php,Asp.net,Curl,Asp.net Web Api,我必须将一个文件对象从php传输到c#webapi。 不知何故,在c#中,文件内容是空的。 这是去掉其他东西后的部分PHP代码 <?php $fileContents = file_get_contents($_FILES['fileToUpload']['tmp_name']); $uploadFile = new UploadFile(); //custom object $uploadFile->fileName = "test"; //strin
<?php
$fileContents = file_get_contents($_FILES['fileToUpload']['tmp_name']);
$uploadFile = new UploadFile(); //custom object
$uploadFile->fileName = "test"; //string
$uploadFile->fileContent = $fileContents; //string
$data_string=json_encode($uploadFile);
$url="http://localhost:62672/api/uploadfile";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_VERBOSE, TRUE);
//curl_setopt($ch, CURLOPT_PORT, 801);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
?>
刚开始学习.NET,因此不知道.NET代码中是否有错误
使用相同的PHP代码,我能够成功地将文件内容发送到.NETWebService,这是一个单独的应用程序
提前谢谢。
阿曼从您的代码列表中,我看到发布的
文件内容
是一个字符串
,您试图将其作为字节[]
接收。您应该将CrmUploadFileModel.fileContent
的类型更改为string
,它应该可以工作。见下文注释
由于您没有显示路由配置,我不知道post操作中缺少的[HttpPost]
属性是否是另一个问题。如果将其添加到代码中,则不会造成任何伤害,我们可以放弃此问题(事实上,如果调试器输入Post
操作,则这不是问题)
注意:如果要发布和接收字节数组,则不能直接在JSON对象中执行,除非在客户端将其编码为字符串并在服务器中解码。如果您仍然希望发送字节数组,则不能期望自动参数绑定,并且必须做额外的工作:正如您在问答中所看到的,您必须将整个发布值转换为byte[]
,因此发送多个属性更加困难(您必须手动解析数组)
public class CrmUploadFileModel
{
public string fileName { get; set; }
public byte[] fileContent { get; set; }
}
public class UploadFileController : BaseController
{
public IHttpActionResult Post([FromBody]CrmUploadFileModel value)
{
// here .. i find that the value.fileContent is null.
}