ASP.NET Core and formdata binding with file and json property

Viewed 7657

I have a following model:

public class MyJson
{
 public string Test{get;set;}
}

public class Dto
{
 public IFormFile MyFile {get;set;}
 public MyJson MyJson {get;set;}
}

On the client side I want to send a file and a json. So I send it in formData with following keys:

var formData = new FormData();
formData["myFile"] = file//here is my file
formData["myJson"] = obj; // object to be serialized to json.

My action looks like this:

public void MyAction(Dto dto) // or with [FromForm], doesn't really matter
{
  //dto.MyJson is null here
  //dto.myFile is set correctly.
}

if I change dto.MyJson to be a string then it work perfectly fine however I have to deserialize it manually into my object manually in the action. The second issue with having it as a string is that I can't use swagger UI to handle it properly because it will ask me for a json string instead of object, anyway having it as a string just doesn't sound right. Is there a native way to handle json and file properly in action parameters instead of parsing it manually with Request.Form?

1 Answers
Related