0
点赞
收藏
分享

微信扫一扫

想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)#yyds干货盘点#

前言

上回,我们使用最小 WEB API 实现文件上传功能(《​​想说爱你不容易 | 使用最小 WEB API 实现文件上传​​》),虽然客户端访问是正常的,但是当打开 Swagger 页面时,发现是这样的:

想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)#yyds干货盘点#_筛选器

没法使用 Swagger 页面测试。

允许 Content Type

正常的 Swagger 页面应该是这样的:

想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)#yyds干货盘点#_筛选器_02

看来,我们需要指定 Content Type:

app.MapPost("/upload",
async (HttpRequest request) =>
{
var form = await request.ReadFormAsync();

return Results.Ok(form.Files.First().FileName);
}).Accepts<HttpRequest>("multipart/form-data");

结果,Swagger 页面变成了这样,增加了一堆 Form 相关属性,唯独没有 ​​file​​ :

想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)#yyds干货盘点#_筛选器_03

看来,只有自定义 Swagger 页面了。

自定义 OperationFilter

在 OpenAPI 3.0 中,文件上传的请求可以用下列结构描述(https://swagger.io/docs/specification/describing-request-body/file-upload/):

想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)#yyds干货盘点#_自定义_04

而在 Swashbuckle 中,可以使用 IOperationFilter 接口实现操作筛选器,控制如何定义 Swagger UI 的行为。

在这里,我们将利用 ​​RequestBody​​ 对象来实现上述的文件上传的请求结构。

public class FileUploadOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
const string FileUploadContentType = "multipart/form-data";
if (operation.RequestBody == null ||
!operation.RequestBody.Content.Any(x =>
x.Key.Equals(FileUploadContentType, StringComparison.InvariantCultureIgnoreCase)))
{
return;
}

if (context.ApiDescription.ParameterDescriptions[0].Type == typeof(HttpRequest))
{
operation.RequestBody = new OpenApiRequestBody
{
Description = "My IO",
Content = new Dictionary<String, OpenApiMediaType>
{
{
FileUploadContentType, new OpenApiMediaType
{
Schema = new OpenApiSchema
{
Type = "object",
Required = new HashSet<String>{ "file" },
Properties = new Dictionary<String, OpenApiSchema>
{
{
"file", new OpenApiSchema()
{
Type = "string",
Format = "binary"
}
}
}
}
}
}
}
};
}
}
}

然后,在启动代码中配置,应用此操作筛选器:

builder.Services.AddSwaggerGen(setup =>
{
setup.OperationFilter<FileUploadOperationFilter>();
});

这将呈现如下 Swagger 页面:

想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)#yyds干货盘点#_自定义_05

结论

今天,我们使用 ​​IOperationFilter​​ 解决了最小 WEB API 实现文件上传的 Swagger 支持。

想了解更多内容,请关注我的个人公众号”My IO“

想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)#yyds干货盘点#_自定义_06


举报

相关推荐

0 条评论