Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an upload button to swagger UI in .NET core web api?

I have an ASP.net core web API with swagger (using swashbuckle).

One of the actions in the Web API is a file upload action:

[Produces("application/json")]
[Route("[controller]")]
public class FilesController : Controller
{
    [HttpPost]
    public void Post(IFormFile file)
    {
        ...
    }
}

When I look up that action in the swagger UI it let's me fill in all the fields of IFormFile, which is not what I want to do to test my API.

So how can I add an upload button to the Swagger UI?

like image 872
Nick N. Avatar asked Dec 14 '22 16:12

Nick N.


1 Answers

For anyone looking for an open api implementation

/// <summary>
/// Add extra parameters for uploading files in swagger.
/// </summary>
public class FileUploadOperation : IOperationFilter
{
    /// <summary>
    /// Applies the specified operation.
    /// </summary>
    /// <param name="operation">The operation.</param>
    /// <param name="context">The context.</param>
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {

        var isFileUploadOperation =
            context.MethodInfo.CustomAttributes.Any(a => a.AttributeType == typeof(FileContentType));

        if (!isFileUploadOperation) return;

        operation.Parameters.Clear();
   
        var uploadFileMediaType = new OpenApiMediaType()
        {
            Schema = new OpenApiSchema()
            {
                Type = "object",
                Properties =
                {
                    ["uploadedFile"] = new OpenApiSchema()
                    {
                        Description = "Upload File",
                        Type = "file",
                        Format = "formData"
                    }
                },
                Required = new HashSet<string>(){  "uploadedFile"  }
            }
        };

        operation.RequestBody = new OpenApiRequestBody
        {
            Content = {  ["multipart/form-data"] = uploadFileMediaType   }
        };
    }
    
    /// <summary>
    /// Indicates swashbuckle should consider the parameter as a file upload
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class FileContentType : Attribute
    {
       
    }
}

Decorate controller using FileContentType attribute

[HttpPost]
[Route("PostFile")]
[FileUploadOperation.FileContentType]
public IActionResult PostFile(IFormFile uploadedFile)

File upload should be generated in the Request body like below..

enter image description here

like image 97
ssilas777 Avatar answered Dec 28 '22 05:12

ssilas777