POST request: How do I have 1 [FromBody] class/object argument + 1 IFormFile argument in the same request?

Viewed 700

I am looking to receive 1 CNCTask class object from the body, but I also need to transfer a file in the same POST request. I have written out my POST route definition as:

[HttpPost("TaskUpload")]
[Consumes("application/json")]
public async Task<ActionResult<CNCTask>> Post([FromBody] CNCTask task, IFormFile file)

With my route defined as such, I just don't get how I will even transfer the file (e.g. when testing from Postman). A file would usually be sent in the body (I think ?), but if I already have my CNCTask object being selected by the [FromBody], how do I negotiate this file transfer as well ?

I'm quite confused as to how to send both the class object and the file. Any tips would be appreciated.

EDIT

text body request that only includes a CNCTask object

{
  "description":"truc",
  "completion":24,
  "machine":{
    "hostname":"some host",
    "port": 1234
  }
}

form-data body request that includes the full Payload (CNCTask + IFormFile)

Form-data

2 Answers

This was tested using a Postman and Visual studio.

You have to create a model class

public class CNCTask
{
        public string Description { get; set; }
        public int Completion { get; set; }
        public Machine Machine { get; set; }
        public IFormFile File { get; set; }
}

public class Machine
{
        public string Hostname { get; set; }
        public int Port { get; set; }
}

action

[HttpPost("TaskUpload")]
public async Task<ActionResult<CNCTask>> Post(CNCTask model)

and you can test it using postman

enter image description here

You can retrive form data as follows

var formdata = Request.Form["formdata"];
var model = JsonConvert.DeserializeObject<ModelEntity>(formdata);

And write your controller this way

public async Task<ActionResult<CNCTask>> Post(IFormFile file)
{
    var formdata = Request.Form["formdata"];
    var model = JsonConvert.DeserializeObject<InitialDemandEntity>(formdata);
            ...
}
Related