這篇文章主要介紹“如何使用最小WEB API實現文件上傳”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“如何使用最小WEB API實現文件上傳”文章能幫助大家解決問題。
我們使用最小 WEB API 實現文件上傳功能,雖然客戶端訪問是正常的,但是當打開 Swagger 頁面時,發現是這樣的:

沒法使用 Swagger 頁面測試。
正常的 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 頁面了。
在 OpenAPI 3.0 中,文件上傳的請求可以用下列結構描述:

而在 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實現文件上傳”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。