Files
emall-api/FutureMailAPI/Helpers/FileUploadOperationFilter.cs

36 lines
1.3 KiB
C#
Raw Normal View History

2025-10-16 09:56:36 +08:00
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.AspNetCore.Http;
using System.Reflection;
using System.Linq;
namespace FutureMailAPI.Helpers
{
/// <summary>
/// Swagger文件上传操作过滤器
/// </summary>
public class FileUploadOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var fileUploadMime = "multipart/form-data";
if (operation.RequestBody == null || !operation.RequestBody.Content.Any(x => x.Key.Equals(fileUploadMime, StringComparison.InvariantCultureIgnoreCase)))
return;
var fileParams = context.MethodInfo.GetParameters()
.Where(p => p.ParameterType == typeof(IFormFile) ||
(p.ParameterType.IsClass && p.ParameterType.GetProperties().Any(prop => prop.PropertyType == typeof(IFormFile))))
.ToList();
if (!fileParams.Any())
return;
operation.RequestBody.Content[fileUploadMime].Schema.Properties =
fileParams.ToDictionary(k => k.Name!, v => new OpenApiSchema()
{
Type = "string",
Format = "binary"
});
}
}
}