經常使用swagger,可以通過設定[ProducesResponseType]
標記介面的返回資訊;swagger也能通過介面的引數列表,自動獲得傳送的資料結構資訊。
不過有一個例外,就是上傳檔案的時候,設定了[Consumes]的內容為multi-part/form-data
,但是swagger並不能正常感知是上傳檔案的。程式碼是這個樣子的:
關於檔案上傳的細節,可以看多年前我寫過一篇有關通過WEBAPI上傳檔案的文章。
[Consumes("multipart/form-data")]
[ODataRoute]
[HttpPost]
public async Task<ActionResult> Post(IFormCollection collection)
{
var file = collection.Files[0];
if(file != null)
{
var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + file.FileName;
var path = Path.Combine(_webHostEnvironment.WebRootPath, "Files", filename);
using FileStream fileStream = new FileStream(path, FileMode.Create);
await file.CopyToAsync(fileStream);
var uri = "Files/" + filename;
var fileEntity = new Models.File { Url = uri, LastModified = DateTime.Now };
_homeworkDataContext.Files.Add(fileEntity);
await _homeworkDataContext.SaveChangesAsync();
return Created(WebUtility.UrlEncode(uri), fileEntity);
}
return BadRequest();
}
實際上,swagger一直提示,上傳的內容是一個array型別,當然API是沒有問題的,可以通過POSTMAN進行傳送,不過不能在網頁上直接操作,總覺得心裡有點不太舒服。
方法
搜尋了一下辦法,比較靠譜的,就是通過增加一個IOperationFilter
來實現目的。
// CODE FROM https://www.talkingdotnet.com/how-to-upload-file-via-swagger-in-asp-net-core-web-api/
public class FileUploadOperation : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.OperationId.ToLower() == "apivaluesuploadpost")
{
operation.Parameters.Clear();
operation.Parameters.Add(new NonBodyParameter
{
Name = "uploadedFile",
In = "formData",
Description = "Upload File",
Required = true,
Type = "file"
});
operation.Consumes.Add("multipart/form-data");
}
}
}
然後,在services.ConfigureSwaggerGen()
引數中,新增
options.OperationFilter<FileUploadOperation>();
方法的原理是通過重寫操作某個特定API的的過濾器,來實現對返回內容的操作。
此方法適用於OAS2,實質上是實現了這裡的規範要求。
我已經用上.NET 5.0了,自帶了swagger都支援的是OpenAPI 3,這個方法不好用了。不過思想應該相同,首先看看OpenAPI 3的規範,檔案上傳需要定義為:
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
fileName:
type: string
format: binary
這個套路和OpenAPI 2完全不一樣,需要重新設定requestBody才行。我們按照要求改造程式碼。
public class FileUploadOperation : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
//判斷上傳檔案的型別,只有上傳的型別是IFormCollection的才進行重寫。
if (context.ApiDescription.ActionDescriptor.Parameters.Any(w => w.ParameterType == typeof(IFormCollection)))
{
Dictionary<string, OpenApiSchema> schema = new Dictionary<string, OpenApiSchema>();
schema["fileName"] = new OpenApiSchema { Description = "Select file", Type = "string", Format = "binary" };
Dictionary<string, OpenApiMediaType> content = new Dictionary<string, OpenApiMediaType>();
content["multipart/form-data"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Properties = schema } };
operation.RequestBody = new OpenApiRequestBody() { Content = content };
}
}
}
執行之後,swagger已經可以正常識別了,通過選擇檔案即可上傳,效果如下:
參考資料
- https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-5.0&tabs=visual-studio
- https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0#upload-large-files-with-streaming
- https://www.talkingdotnet.com/how-to-upload-file-via-swagger-in-asp-net-core-web-api/