想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)
前言
上回,我們使用最小 WEB API 實(shí)現(xiàn)文件上傳功能(《想說愛你不容易 | 使用最小 WEB API 實(shí)現(xiàn)文件上傳》),雖然客戶端訪問是正常的,但是當(dāng)打開 Swagger 頁面時(shí),發(fā)現(xiàn)是這樣的:
沒法使用 Swagger 頁面測(cè)試。
允許 Content Type
正常的 Swagger 頁面應(yīng)該是這樣的:
看來,我們需要指定 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");結(jié)果,Swagger 頁面變成了這樣,增加了一堆 Form 相關(guān)屬性,唯獨(dú)沒有 file :
看來,只有自定義 Swagger 頁面了。
自定義 OperationFilter
在 OpenAPI 3.0 中,文件上傳的請(qǐng)求可以用下列結(jié)構(gòu)描述(https://swagger.io/docs/specification/describing-request-body/file-upload/):
而在 Swashbuckle 中,可以使用 IOperationFilter 接口實(shí)現(xiàn)操作篩選器,控制如何定義 Swagger UI 的行為。
在這里,我們將利用 RequestBody 對(duì)象來實(shí)現(xiàn)上述的文件上傳的請(qǐng)求結(jié)構(gòu)。
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"}}}}}}}};}} }然后,在啟動(dòng)代碼中配置,應(yīng)用此操作篩選器:
builder.Services.AddSwaggerGen(setup?=> {setup.OperationFilter<FileUploadOperationFilter>(); });這將呈現(xiàn)如下 Swagger 頁面:
結(jié)論
今天,我們使用 IOperationFilter 解決了最小 WEB API 實(shí)現(xiàn)文件上傳的 Swagger 支持。
想了解更多內(nèi)容,請(qǐng)關(guān)注我的個(gè)人公眾號(hào)”My IO“
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 继 SpringBoot 3.0,Ela
- 下一篇: C#中类的override和virtua