1

I am trying to setup a Controller Method with NSwag where I can Upload a multipart/form-data file

    [HttpPost]
    [Route("{number:long}")]
    [ValidateMimeMultipartContentFilter]
    [SwaggerResponse(500, typeof(string), Description = "Error")]
    public async Task<IHttpActionResult> Upload(long number)
    {
             //My backend code for file upload
    }

But I am not able to upload a file through NSwag webinterface. In ASP.NET Core you have a Attribute for this issue I think, but how can I get this support in Web Api 2

squadwuschel
  • 3,328
  • 3
  • 34
  • 45

1 Answers1

4

NSwag is not supporting file upload for Web API 2 out of the box, you need to create a operation processor which creates the parameter for the file upload.

I've created my own Operation Processor

public class SwaggerFilChunkUploadOperationProcessor : IOperationProcessor
{
    public Task<bool> ProcessAsync(OperationProcessorContext context)
    {
        var data = context.OperationDescription.Operation.Parameters;

        //File upload
        data.Add(new SwaggerParameter()
        {
            IsRequired = true,
            Name =  "file",
            Description = "filechunk",
            Type = JsonObjectType.File,
            Kind = SwaggerParameterKind.FormData
        });

        //custom formdata (not needed for the file upload)
        data.Add(new SwaggerParameter()
        {
            IsRequired = true,
            Name = "file-name",
            Description = "the original file name",
            Type = JsonObjectType.String,
            Kind = SwaggerParameterKind.FormData
        });

        return Task.FromResult(true);
}

//defined as Attribute Usage, so you can use the attribute in your Controller
public class SwaggerFileChunkUploadAttribute : SwaggerOperationProcessorAttribute
{
    public SwaggerFileChunkUploadAttribute() : base(typeof(SwaggerFilChunkUploadOperationProcessor))
    {
    }
}

In your controller you can now use

   [ValidateMimeMultipartContentFilter]
   [SwaggerFileChunkUpload]
    public async Task<IHttpActionResult> Upload(long ordernumber)
    {
         //process your file here!
    }
squadwuschel
  • 3,328
  • 3
  • 34
  • 45
  • I'm struggling to adapt this to allowing for an array of files. Has anyone had any success with that? – Jake Stevenson Mar 25 '19 at 19:48
  • The sample shows that this is possible for a predefined number of files, it not possible, however, for an unlimited set and not applicable in my opinion – AbuDawood May 11 '20 at 23:55