Search code examples
c#asp.net-coreswagger

How to test swagger with IFormFile and model


I've made a webapi. I currently have two endpoints, first endpoint does an httppost that accepts a model. The second is an endpoint that accepts a IFormFile. both endpoint works.

I'm currently trying to make a third endpoint that accepts a model and has an IFormFIle. When I enter swagger, I don't see the choose file option for Request Body

enter image description here

public async Task<ActionResult<Document>> AddOne([FromBody] DocumentAddRequest docAddRequest) {....}

public class DocumentAddRequest
{
    public string Name { get; set; }
    public IFormFile File {get; set;}
}

I've also tried adding within the controller but I still don't see the choose file button when entering swagger.

public async Task<ActionResult<Document>> AddOne([FromBody] DocumentAddRequest docAddRequest, IFormFile file) {....}

May I ask how do I test my endpoint for file upload that also consumes a model.


Solution

  • Change your code like below, and the issue could be fixed.

    [HttpPost("AddOne")]
    public async Task<ActionResult<Document>> AddOne([FromForm] DocumentAddRequest docAddRequest, IFormFile file) {
        ...
    }
    

    Reason

    We should use multipart/form-data type data when uploading the model in your scenario, so using [FromForm] attribute can solve this problem.

    Test Result

    enter image description here

    enter image description here