发布时间:2022-03-04 09:48:49来源:网络阅读(891)
API代码
[HttpPost]
public ApiResult UpFile(List files)
{
if (files.Count != 1) throw new MyException("只允许上传一个文件");
var basePath = Path.Combine(_hostingEnvironment.WebRootPath);
var savePath = Path.Combine(basePath, "zlfile");
var fileName=DateTime.Now.ToFileTime();
var file=files[0];
var fileType=Path.GetExtension(file.FileName).ToLower();
using (var stream = new FileStream(Path.Combine(savePath, $"{fileName}{fileType}"), FileMode.CreateNew))
{
file.CopyToAsync(stream).Wait();
}
return Response($"/zlfile/{fileName}{fileType}");
}
然后再看swagger ,度娘下,就是需要增加个 IOperationFilter 来实现,看代码
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();
方法的原理是通过重写操作某个特定API的的过滤器,来实现对返回内容的操作。
由于.NET 5 自带了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 schema = new Dictionary();
schema["fileName"] = new OpenApiSchema { Description = "Select file", Type = "string", Format = "binary" };
Dictionary content = new Dictionary();
content["multipart/form-data"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Properties = schema } };
operation.RequestBody = new OpenApiRequestBody() { Content = content };
}
}
}
执行之后,swagger已经可以正常识别了,通过选择文件即可上传,效果如下:
关键字:
上一篇: .NET 500.19错误
下一篇: .NET 6中读取BODY内容
1053
1596
980
3415
2048
1496
1625
1447
956
1943
9593
5996
5523
5116
4567
4274
3415
3336
3335
3269