想说爱你不容易 | 使用最小 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 頁面:
結論
今天,我們使用 IOperationFilter 解決了最小 WEB API 實現文件上傳的 Swagger 支持。
想了解更多內容,請關注我的個人公眾號”My IO“
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 继 SpringBoot 3.0,Ela
- 下一篇: C#中类的override和virtua