Search code examples
c#.netswaggerasp.net-web-api2nswag

Hot to write a FileUpload method in a WebAPI using NSwag?


I'm currently working on a ASP.NET WebAPI 2 (.NET 4.7.1) using NSwag 13.19.0. I managed to integrate a file upload into my WebAPI, like described here by @squadwuschel: NSwag Wep Api 2 multipart/form-data Attribute / file upload

Strangely, it only works, if I use the SchemaType.Swagger2. If I use SchemaType.OpenApi3, no file upload button will be rendered in the Swagger UI in the browser:

File Upload in Swagger UI for SchemaType.Swagger2: File Upload in Swagger UI for SchemaType.Swagger2

File Upload in Swagger UI for SchemaType.OpenApi3: File Upload in Swagger UI for SchemaType.OpenApi3

I expected that the file upload always will be rendered the same way in the Swagger UI, no matter what SchemaType I use. So I have no further ideas, what I can do to solve this problem. Has anyone ever had the same problem and perhaps found a solution?

Thanks in advance.

Best regards, Tom


Solution

  • I found the solution for the problem:

    For SchemaType.OpenApi3 (OpenApi Sepcification 3.0) you'll have to configure the parameter as a body parameter in the IOperationProcessor implementation, instead of adding SwaggerParameters to context.OperationDescription.Operation.Parameters:

    context.OperationDescription.Operation.RequestBody = new OpenApiRequestBody
    {
        IsRequired = true,
        Content =
        {
            ["multipart/form-data"] = new OpenApiMediaType
            {
                Schema = new JsonSchema
                {
                    Type = JsonObjectType.Object,
                    Properties =
                    {
                        ["your parameter"] = new JsonSchemaProperty
                        {
                            Type = JsonObjectType.String,
                            Format = JsonFormatStrings.Binary,
                            IsNullableRaw = false,
                            Description = "some description",
                        }
                    }
                }
            }
        }
    };