1

我正在尝试使用 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 网络界面上传文件。我认为在 ASP.NET Core 中,您有一个针对此问题的属性,但是如何在 Web Api 2 中获得此支持

4

1 回答 1

4

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!
    }
于 2019-01-25T18:05:06.020 回答