Search code examples
c#asp.net-coreswagger-ui

How to upload a small file through an ASP.net C# controller through a Swagger UI?


I am trying to implement a controller to upload a small file via IFormFile. When I only have the IFormFile and string as parameters it works (see image #2). When I add a command object it doesnt (see image #1).

    [HttpPost()]
    public async Task<IActionResult> Upload(IFormFile file, string fileName, AddResumeCommand command)
    {
        return Accepted();
    }

I am using Swashbuckle.AspNetCore version 5.6.3.

The Swagger UI looks like this: enter image description here

Now the following works:

    [HttpPost()]
    public async Task<IActionResult> Upload(IFormFile file, string fileName)
    {
        return Accepted();
    }

The Swagger UI is:

enter image description here

I would like the first screen to be able to look like the second where there is the "file selection".


Solution

  • The answer is to annotate my controller with [Consumes("multipart/form-data")] along with the following function definition:

            public async Task<IActionResult> Upload([FromForm] AddResumeFileCommand fileCommand) { }
    

    where AddResumeFileCommand is:

    public class AddResumeFileCommand
    {
        public string FileName { get; set; }
    
        public IFormFile FormFile { get; set; }
    
        public AddResumeFileCommand( string fileName, IFormFile formFile)
        {
            FileName = fileName;
            FormFile = formFile;
        }
    }