Search code examples
asp.net-coreswagger-uiopenapi

OpenApi 3 multipart form request for complex type array


I created a new Asp.Net Core 5.0 Web API project and I try to upload a file together with other properties. One of this properties is a list of other elements which I have defined. The data model looks like this:

    public class Person
    {
        public string Surname { get; set; }
        public string FamilyName { get; set; }

        public IFormFile Image { get; set; }

        public List<Item> Items { get; set; } = new List<Item>();
    }

    public class Item
    {
        public string Value { get; set; }
        public string Description { get; set; }
    }

It seems that the swagger doc generates the proper file with the proper UI. Unfortunately I don't know which format the data must be so that the ASP.NET Core model binder translates it into a valid model. I tried to insert some json object into the "Items" box but my list stays empty all the time.

The controller action is pretty standard:

        [HttpPost]
        public ActionResult Post([FromForm] Person p)
        {
            if (ModelState.IsValid)
            {
                return Ok();
            }

            return BadRequest();
        }

The UI looks like this. enter image description here


Solution

  • I didn't found a neat solution so far but I wrote a custom model binder like described here. So basically the request has two parts. One with the file and one with the whole JSON data.

    https://thomaslevesque.com/2018/09/04/handling-multipart-requests-with-json-and-file-uploads-in-asp-net-core/