3

I have to transfer a file object from php to c# webapi. Somehow, in c#, the file contents are coming as Null. This is the partial PHP code after taking out the other stuff

 <?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',

    ));

?>

And here is the c# controller code & model code

 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. 
}

Just started learning .NET and hence dont know if anything is wrong in the .NET code.

Using the same PHP code, i am able to send succesfuly the file contents to a .NET webservice, which is a separate application.

Thanks in advance. Aman

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

0

From your code conmments, I see that the posted fileContent is a string, and you're trying to receive it as byte[]. You should change the type of CrmUploadFileModel.fileContent to string, and it shoukd work. See Note below.

As you're not showing the route configuration, I don't know if a missing [HttpPost] attribute in your post action is another problem. If you add it in your code, it will do no harm, and we can discard this problem (in fact, if your debugger enters the Post action, this is not a problem).

Note: If you want to post and receive a byte array, you cannot do it directly in a JSON object, unless you encode it in the client as a string and decode it in the server. If you still want to send a byte array, you cannot expect the automatic parameter binding, and you have to do extra work: How to Get byte array properly from an Web Api Method in C#? As you can see in that Q&A you have to convert the whole posted value to byte[], so sending several properties is even harder to do (you'd have to parse the array by hand).

Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117