NSwag Wep Api 2 multipart / form-data属性/文件上传

时间:2019-01-24 14:05:05

标签: c# swagger nswag

我正在尝试使用NSwag设置控制器方法,我可以在其中上传多部分/表单数据文件

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

但是我无法通过NSwag Web界面上传文件。我认为在ASP.NET Core中,您有一个针对此问题的属性,但是如何在Web Api 2中获得此支持

1 个答案:

答案 0 :(得分:2)

NSwag不支持Web API 2的文件上载,您需要创建一个操作处理器来创建文件上载的参数。

我已经创建了自己的运算处理器

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))
    {
    }
}

您现在可以在控制器中使用

   [ValidateMimeMultipartContentFilter]
   [SwaggerFileChunkUpload]
    public async Task<IHttpActionResult> Upload(long ordernumber)
    {
         //process your file here!
    }