代码之家  ›  专栏  ›  技术社区  ›  squadwuschel

NSWAG WEP API 2多部分/表单数据属性/文件上载

  •  1
  • squadwuschel  · 技术社区  · 6 年前

    我试图用nswag设置一个controller方法,在这里我可以上传一个多部分/表单数据文件

        [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 webinterface上传文件。我认为,在asp.net内核中,有一个属性可以解决这个问题,但是如何在web api 2中获得这种支持呢?

    1 回复  |  直到 6 年前
        1
  •  1
  •   squadwuschel    6 年前

    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!
        }