gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:37:21 25 4
gpt4 key购买 nike

我正在尝试使用 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 网络界面上传文件。我认为在 ASP.NET Core 中你有一个针对这个问题的属性,但我怎样才能在 Web Api 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))
{
}
}

在你的 Controller 中你现在可以使用

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

关于c# - NSwag Wep Api 2 multipart/form-data 属性/文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com