好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用最小 WEB API 实现文件上传的Swagger支持

前言:

上回,我们使用最小 WEB API 实现文件上传功能《 ? ?使用最小 WEB API 实现文件上传会遇到的坑 ??》,虽然客户端访问是正常的,但是当打开 Swagger 页面时,发现是这样的:

没法使用 Swagger 页面测试。

一、允许 Content Type

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

看来,我们需要指定 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?? :

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

二、自定义 OperationFilter

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

而在 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支持的文章就介绍到这了,更多相关使用最小 WEB API 实现文件上传 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于使用最小 WEB API 实现文件上传的Swagger支持的详细内容...

  阅读:47次