2

I don't seem to be able to find out why my controller receives null data. I am able to reach the controller, but no data is transmitted. Everything works fine at the controller end when I am using Postman to test the API with Body and with correct key/data content.

enter image description here

My controller method:

[Route("home/api/files")]
public class FileController : ControllerBase
{
  [HttpPost]
  public async Task<IActionResult> Post([FromForm] FileModel file)
  {
    if (file == null)
      return BadRequest("Given data is null");
    if (string.IsNullOrEmpty(file.Name))
      return BadRequest("File name is undefined");
    if (string.IsNullOrEmpty(file.FolderPath))
      return BadRequest("FolderPath is undefined");
    if (file.File.Length < 0)
      return BadRequest("File content is empty");
    ...
  }
}

The FileModel:

public class FileModel
{
  public string Name { get; set; }
  public string Extension { get; set; }
  public string FolderPath { get; set; }
  public IFormFile File { get; set; }
}

And the client-side Axios call:

export function uploadFile(folderPath, data) {
  console.log("upLoadFile", folderPath, data);

  const formData = new FormData();
  formData.set('name', data.file);
  formData.set('extension', data.extension);
  formData.set('folderPath', folderPath);
  formData.append('file', data);

  return axios.post(
    "api/files",
    formData,
    { headers: { 'Content-Type': 'multipart/form-data}' }})
    //{ headers: { 'Content-Type': 'multipart/form-data; boundary=${form._boundary}' }})
    .then((response) => {
      console.log(response.data);
      console.log(response.status);
    })
    .catch((error) => {
      console.log(error);
    });
}

I assume the issue lies somewhere with the data types I am sending? Particularly, with the FileModels File property type IFormFile. All ideas are welcomed!

The used version of Axios 0.19.2

ajr
  • 874
  • 2
  • 13
  • 29
  • did you try to replace `[FromForm]` with `[FromBody]`? – Hamed Moghadasi Feb 08 '20 at 19:38
  • with ```[FromBody]``` I receive a reply from the controller: ```415 Unsupported Media Type```. Same reply with Postman and with the Axios. – ajr Feb 08 '20 at 19:43
  • 1
    try to change your `content-type` to `application/json`, base on https://stackoverflow.com/a/46278263/6797509 – Hamed Moghadasi Feb 08 '20 at 19:47
  • Hmm, I tried this: ```{ headers: { 'Content-Type': 'application/json' }}``` and it didn't have an impact. I am still reaching the controller but ```file```all properties are ```null``` – ajr Feb 08 '20 at 19:55
  • 1
    umm, use `[FromBody]` and set `content-type` to `application/json` and then by `postman` try to send data as `row`. and please pay attention to set data type to `JSON (application/type)` --> https://i.stack.imgur.com/RdwPZ.png – Hamed Moghadasi Feb 08 '20 at 20:38
  • I didn't experiment with this approach any further because I wanted to stick with the ```form-data```. I got it working with it and will post an answer about the issue. I could later at some point experiment with JSON data, therefore thank you for the tips! :) – ajr Feb 10 '20 at 08:18
  • good job. your welcome ;) – Hamed Moghadasi Feb 10 '20 at 08:19

2 Answers2

2

I believe the main problem was related to the data types with my initial try. It is important that the given data is in the right format/type.

Defining the data properly as following helped:

const file = new Blob([data.contents], { type: 'text/csv' });

const formData = new FormData();
formData.set('Name', data.file);
formData.set('Extension', data.extension);
formData.set('FolderPath', folderPath);
formData.append('File', file);

const requestConfig = {
    headers: {
    "Content-Type": "multipart/form-data"
  }
};

when formData is defined as above, the following Axios POST works out without issues or changes to the controller, [FromForm] works as expected.

return axios.post(
  "api/files",
  formData,
  requestConfig)
.then((response) => {
  console.log(response.data);
})
.catch((error) => {
  console.log(error);
});
ajr
  • 874
  • 2
  • 13
  • 29
0

Faced a similar issue once. I had the following ajax setup:

$.ajax
        ({
            async: true,
            crossDomain: true,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            encType: 'multipart/form-data',
            url: apiURL,
            method: "POST",
            data: dataObject,
            processData: false,
            contentType: false
        });

The problem was sending:

  headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }

and then:

encType: 'multipart/form-data'

There was a confusion there as to the format of data to expect, so the end point was receiving a request model with fields all null.

Changed to the following to resolve the issue:

$.ajax
        ({
            async: true,
            crossDomain: true,
            encType: 'multipart/form-data',
            url: apiURL,
            method: "POST",
            processData: false,
            contentType: false,
            data: dataObject
        });
Bernard Oreva
  • 124
  • 1
  • 4