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?
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With